srm*_*mjr 3 java string loops indexof
我正在尝试使用indexOf来查找句子中所有出现的字符'the'.例如,如果句子是"我去那里的另一天",它应该返回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 -----");
Run Code Online (Sandbox Code Playgroud)
您可以跟踪索引:
int index = theString.indexOf("the");
while(index >= 0) {
index = theString.indexOf("the", index+1);
counter2++;
}
Run Code Online (Sandbox Code Playgroud)
你采取了一种复杂的方法.试试这个:
int count = str.split("the").length - 1;
Run Code Online (Sandbox Code Playgroud)
如果你绝对必须使用indexOf():
str = str.toLowerCase();
int count = 0;
for (int i = str.indexOf("the"); i >= 0; i = str.indexOf("the", i + 1))
count++;
Run Code Online (Sandbox Code Playgroud)