3 回答
TA贡献1946条经验 获得超4个赞
根据您的评论,我假设您的要求如下:
您的字符串包含多个由竖线字符分隔的部分
|
,例如"a|e|b|c|a|c|a|d"
你想删除所有重复的字符串,同时保留元素的顺序,例如你想要
"a|e|b|c|d"
为此,您可以在管道处拆分字符串,将元素收集到 a 中LinkedHashSet
,然后使用管道重新加入元素。
使用 Java 8 的示例:
//The pipe needs to be escaped because split() interprets the input as a regex
Set<String> elements = new LinkedHashSet<>( Arrays.asList( input.split( "\\|" ) ) );
//rejoin using the pipe
String output = elements.stream().collect( Collectors.joining( "|" ) );
TA贡献1824条经验 获得超5个赞
要查看是否至少key包含一个字符串两次,并删除第二次出现,请使用两次,第二次调用在第一次出现后开始搜索:sindexOf
static String removeSecond(String key, String s) {
int idxFirst = key.indexOf(s);
if (idxFirst != -1) {
int idxSecond = key.indexOf(s, idxFirst + s.length());
if (idxSecond != -1) {
return key.substring(0, idxSecond) +
key.substring(idxSecond + s.length());
}
}
return key; // Nothing to remove
}
测试
System.out.println(removeSecond("mississippi", "ss")); // prints: missiippi
System.out.println(removeSecond("mississippi", "i")); // prints: missssippi
System.out.println(removeSecond("mississippi", "pp")); // prints: mississippi
更新
如果您想删除所有重复项,即只保留第一次出现的项,请继续搜索。为了获得构建新字符串的最佳性能,请使用StringBuilder.
static String removeDuplicates(String key, String s) {
int idx = key.indexOf(s);
if (idx == -1)
return key; // Nothing to remove
StringBuilder buf = new StringBuilder();
int prev = 0;
for (int start = idx + s.length(); (idx = key.indexOf(s, start)) != -1; prev = start = idx + s.length())
buf.append(key.substring(prev, idx));
return (prev == 0 ? key : buf.append(key.substring(prev)).toString());
}
测试
System.out.println(removeDuplicates("mississippi", "ss")); // prints: missiippi
System.out.println(removeDuplicates("mississippi", "i")); // prints: misssspp
System.out.println(removeDuplicates("mississippi", "s")); // prints: misiippi
System.out.println(removeDuplicates("mississippi", "ab")); // prints: mississippi
TA贡献1966条经验 获得超4个赞
如果要删除除第一个以外的所有事件:
public static String removeExceptFirst(String master, String child) throws Exception {
int firstIndex = master.indexOf(child);
int lastIndexOf = master.lastIndexOf(child);
if (firstIndex == lastIndexOf) {
if (firstIndex == -1) {
throw new Exception("No occurrence!");
} else {
throw new Exception("Only one occurrence!");
}
}
while (true) {
firstIndex = master.indexOf(child);
lastIndexOf = master.lastIndexOf(child);
if (firstIndex == lastIndexOf) {
return master;
}
master = master.substring(0, lastIndexOf) + master.substring(child.length() + lastIndexOf);
}
}
添加回答
举报