3 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
根據(jù)您的評(píng)論,我假設(shè)您的要求如下:
您的字符串包含多個(gè)由豎線字符分隔的部分
|
,例如"a|e|b|c|a|c|a|d"
你想刪除所有重復(fù)的字符串,同時(shí)保留元素的順序,例如你想要
"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貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊
要查看是否至少key包含一個(gè)字符串兩次,并刪除第二次出現(xiàn),請(qǐng)使用兩次,第二次調(diào)用在第一次出現(xiàn)后開始搜索: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
}
測(cè)試
System.out.println(removeSecond("mississippi", "ss")); // prints: missiippi
System.out.println(removeSecond("mississippi", "i")); // prints: missssippi
System.out.println(removeSecond("mississippi", "pp")); // prints: mississippi
更新
如果您想刪除所有重復(fù)項(xiàng),即只保留第一次出現(xiàn)的項(xiàng),請(qǐng)繼續(xù)搜索。為了獲得構(gòu)建新字符串的最佳性能,請(qǐng)使用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());
}
測(cè)試
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貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果要?jiǎng)h除除第一個(gè)以外的所有事件:
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);
}
}
添加回答
舉報(bào)