我试图使用indexOf查找所有出现的字符''在一个句子里。例如,如果句子是"有一天我去那里",它应该返回3.
我能够做到这一点直到它找到第一个索引,但我不确定如何编写循环。我最初有一个搜索整个字符串的for循环,但它返回的是完整的字符串字符长度,而不是我指定字符的出现次数。如何编写一个可以找到所有单词出现的循环?谢谢。
import java.util.Scanner;
public class TheFinder
{
public static void main (String[] args)
{
String theString = "";
Scanner enter = new Scanner(System.in);
System.out.println("Please enter a sentence: ");
theString = enter.nextLine();
int counter2 = 0;
theString.indexOf("the");
if (theString.indexOf("the")!= -1)
counter2++;
System.out.printf("The characters 'the' were found %d times", counter2);
System.out.println();
System.out.println("This was programmed by -----");
答案 0 :(得分:8)
您可以跟踪索引:
int index = theString.indexOf("the");
while(index >= 0) {
index = theString.indexOf("the", index+1);
counter2++;
}
答案 1 :(得分:5)
你采取了一种复杂的方法。试试这个:
int count = str.split("the").length - 1;
如果您绝对必须使用indexOf()
:
str = str.toLowerCase();
int count = 0;
for (int i = str.indexOf("the"); i >= 0; i = str.indexOf("the", i + 1))
count++;
答案 2 :(得分:1)
indexOf
can take a second argument说明了从字符串开始的位置。因此,在找到第一个匹配项后,您可以告诉indexOf
仅搜索该索引之后的字符串等。
此代码应该有效:
public static void main(String[] args) {
String theString = "The other day I went over there.";
theString = theString.toLowerCase();
int index = -1;
int count = 0;
while (true) {
index = theString.indexOf("the", index + 1);
if (index == -1) {
break;
} else {
count += 1;
}
}
System.out.printf("The string 'the' was found %d times.\n", count);
// Output:
// The string 'the' was found 3 times.
}
答案 3 :(得分:1)
indexOf(String str)
方法查找str
的第一个出现的索引。因此,如果你想找到{em> all str
的出现,那么我建议你实现一个循环,一旦你找到str
的实例,你就切断字符串str
内theString
再次theString
,直到它不再在int index = theString.indexOf("the")
int count = 0;
while(index >= 0 && theString.length() > 0){
count++;
theString = theString.substring(0, index + "the".length());
index = theString.indexOf("the");
}
中。这是它应该是什么样子,
{{1}}
答案 4 :(得分:1)
如果你想特别使用indexOf
(我认为这是一个赋值),你可以使用递归方法。
public static String numMatches (String str, String query) {
int index = str.indexOf(query);
if (index == -1)
return 0;
else
return 1 + numMatches(str.substring(index + query.length), query);
}
答案 5 :(得分:0)
也许你可以做这样的事情,你可以使用indexOf(String str)
String word = "We are students of the Department of Informatics. All students should know how to program in Java and C.";
int findit = word.indexOf("students");
int count = 0;
for(int i=0; i<=findit; i++)
{
findit = word.indexOf("students" , findit + 1);
count = count + 1;
}
System.out.print(count);
答案 6 :(得分:0)
这将检查字符串中出现的字符串数。
String str = oIn.nextLine();
String st = oIn.nextLine();
int countS = 0;
int index3 = str3.indexOf(st);
while (index >= 0){
index = str.indexOf(st, index+1);
countS++;
}
System.out.println("The number of occurrences of "+st +" in the string " +str3 +" are "+countS);