有没有关于如何在不使用String替换的情况下替换字符串中的单词的解决方案?
你们都可以看到这就像硬编码一样。有没有什么方法可以动态制作它?我听说有一些库文件可以动态制作但我不太确定。
任何专家都能给我一些解决方案吗?非常感谢你,祝你有愉快的一天。
for (int i = 0; i < results.size(); ++i) {
// To remove the unwanted words in the query
test = results.toString();
String testresults = test.replace("numFound=2,start=0,docs=[","");
testresults = testresults.replace("numFound=1,start=0,docs=[","");
testresults = testresults.replace("{","");
testresults = testresults.replace("SolrDocument","");
testresults = testresults.replace("numFound=4,start=0,docs=[","");
testresults = testresults.replace("SolrDocument{", "");
testresults = testresults.replace("content=[", "");
testresults = testresults.replace("id=", "");
testresults = testresults.replace("]}]}", "");
testresults = testresults.replace("]}", "");
testresults = testresults.replace("}", "");
答案 0 :(得分:0)
在这种情况下,您需要学习regular expression和内置字符串函数String.replaceAll()来捕获所有可能不需要的单词。 例如:
test.replaceAll("SolrDocument|id=|content=\\[", "");
答案 1 :(得分:0)
只需创建并使用自定义的String.replace()方法,该方法恰好使用其中的String.replace()方法:
public static String customReplace(String inputString, String replaceWith, String... stringsToReplace) {
if (inputString.equals("")) { return replaceWith; }
if (stringsToReplace.length == 0) { return inputString; }
for (int i = 0; i < stringsToReplace.length; i++) {
inputString = inputString.replace(stringsToReplace[i], replaceWith);
}
return inputString;
}
在上面的示例方法中,您可以在 stringsToReplace 参数中提供任意数量的字符串,只要它们用逗号(,)分隔即可。它们将全部替换为您为 replaceWith 参数提供的内容。
以下是如何使用它的示例:
String test = "This is a string which contains numFound=2,start=0,docs=[ crap and it may also "
+ "have numFound=1,start=0,docs=[ junk in it along with open curly bracket { and "
+ "the SolrDocument word which might also have ]}]} other crap in there too.";
testResult = customReplace(strg, "", "numFound=2,start=0,docs=[ ", "numFound=1,start=0,docs=[ ",
+ "{ ", "SolrDocument ", "]}]} ");
System.out.println(testResult);
您还可以传递单个字符串数组,其中包含元素中所有不需要的字符串,并将该数组传递给 stringsToReplace 参数,例如:
String test = "This is a string which contains numFound=2,start=0,docs=[ crap and it may also "
+ "have numFound=1,start=0,docs=[ junk in it along with open curly bracket { and "
+ "the SolrDocument word which might also have ]}]} other crap in there too.";
String[] unwantedStrings = {"numFound=2,start=0,docs=[ ", "numFound=1,start=0,docs=[ ",
"{ ", "SolrDocument ", "]}]} "};
String testResult = customReplace(test, "", unwantedStrings);
System.out.println(testResult);