例如,我有一个字符串数组
String[] arr = ["question", "This", "is", "a"];
我有一个字符串,例如String q = "a foo This bar is This foo question a bar question foo";
(我知道这个例子)。
对我来说,最好的方法是将arr
与q
匹配,然后按顺序打印出所有arr[i]
,但不?因为每次我尝试这样做时,它都会返回原始数组,按照它们最初出现在arr
中的顺序,而不是按它们出现的顺序出现。
简单来说,我希望我的结果类似["a", "This", "is", "This", "question", "a", "question"]
,而我只是得到原始数组。
我的代码:
public static void ParseString(String[] arr, String q) {
for (int i = 0; i < arr.length; i++) {
if (q.contains(arr[i])) {
System.out.println(arr[i]);
}
}
}
我意识到这可能是一个非常明显的错误,所以提前感谢您的耐心等待。
答案 0 :(得分:0)
不要遍历数组,循环遍历字符串,如
String q = "a foo This bar is This foo question a bar question foo";
String[] arr = {"question", "This", "is", "a"};
List<String> list = Arrays.asList(arr);
for(String s:q.split(" ")){
if(list.contains(s)){
System.out.println(s);
}
}
你本可以避免使用List
,然后遍历数组,但我发现代码更加清晰。
答案 1 :(得分:0)
您可以将字符串拆分为每个单词的数组,然后循环遍历字符串数组中的每个单词。
String[] arr = {"question", "This", "is", "a"};
String q = "a foo This bar is This foo question a bar question foo";
String[] splitString = q.split(" ");
for (String wordString: splitString) {
for (String wordArray : arr) {
if (wordString.equalsIgnoreCase(wordArray)) {
System.out.println(wordArray);
}
}
}
答案 2 :(得分:0)
如何(1)计算出现次数(2)打印结果?
public void countWords() {
String[] queries = { "question", "This", "is", "a" };
String data = "a foo This bar is This foo question a bar question foo";
//prepare index
Map<String, Integer> index= new HashMap<>();
for (String w : data.split(" ")) {
Integer count=index.get(w);
if(count==null){
index.put(w, 1);
}else{
index.put(w, count+=1);
}
}
//query index
for(String w:queries){
int i=index.get(w);
System.out.println(String.format("%d\t%s", i,w));
}
}
打印
2 question
2 This
1 is
2 a