【发布时间】:2018-07-24 09:26:45
【问题描述】:
我一直在寻找解决方案来在句子中找到像 howareyou 这样的字符串并将它们从中删除。例如:
我们有一句话——Hello there, how are you?
和复合 - how are you
结果,我想要这个字符串 - Hello there, ? 去除化合物。
我当前的解决方案是将字符串拆分为单词并检查复合词是否包含每个单词,但效果不佳,因为如果您还有其他与该复合词匹配的单词,它们也会被删除,例如:
如果我们将在此字符串中查找foreseenfuture - I have foreseen future for all of you,那么根据我的解决方案for 也将被删除,因为它在化合物内部。
代码
String[] words = text.split("[^a-zA-Z]");
String compound = "foreseenfuture";
int startIndex = -1;
int endIndex = -1;
for(String word : words){
if(compound.contains(word)){
if(startIndex == -1){
startIndex = text.indexOf(word);
}
endIndex = text.indexOf(word) + word.length() - 1;
}
}
if(startIndex != -1 && endIndex != -1){
text = text.substring(0, startIndex) + "" + text.substring(endIndex + 1, text.length() - 1);
}
那么,有没有其他方法可以解决这个问题?
【问题讨论】:
-
试试this。
-
复合应该没有空格。
-
“应该”或“是”没有空格?
-
是,对不起。就像在我的代码中一样 -
String compound = "foreseenfuture"; -
从字符串中删除
foreseenfuture后的最终结果是什么?
标签: java regex string search text