![](/img/trans.png)
[英]How to convert string to array of substrings based on the length of substring in java?
[英]How to replace any of the substrings in a string with empty substring “” (remove substring) in java
我想在字符串中只允許幾個子字符串(允許的單詞)。 我想刪除其他子字符串。
因此,我想替換所有單詞,除了少數幾個單詞,例如“ abc”,“ def”和“ ghi”等。
我想要這樣的東西。 str.replaceAll(“ ^ [abc],”“)。replaceAll(” ^ [def],“”)..........(語法不正確)
輸入:字符串:“ abcxyzorkdefa ”允許的單詞:{“ abc ”,“ def ”}
輸出:“ abcdef ”;
如何實現呢? 提前致謝。
這是一種更像C的方法,但是使用Java的String.startsWith
來匹配模式。 該方法沿提供的字符串行進,將找到的匹配模式保存到結果字符串中。
您只需要確保任何包含較小模式的較長模式都位於patterns數組的前面(因此, "abcd"
先於"abc"
)。
class RemoveNegated {
public static String removeAllNegated(String s, List<String> list) {
StringBuilder result = new StringBuilder();
// Move along the string from the front
while (s.length() > 0) {
boolean match = false;
// Try matching a pattern
for (String p : list) {
// If the pattern is matched
if (s.toLowerCase().startsWith(p.toLowerCase())) {
// Save it
result.append(p);
// Move along the string
s = s.substring(p.length());
// Signal a match
match = true;
break;
}
}
// If there was no match, move along the string
if (!match) {
s = s.substring(1);
}
}
return result.toString();
}
public static void main(String[] args) {
String s = "abcxyzorkdefaef";
s = removeAllNegated(s, Arrays.asList("abc", "def", "ghi"));
System.out.println(s);
}
}
印刷品: abcdef
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.