indexOf查找字符串中单词的所有出现 [英] indexOf to find all occurrences of a word in a String
问题描述
我正在尝试使用indexOf查找句子中所有出现的字符"the".例如,如果句子是那天我去那边",它应该返回3.
I'm trying to use indexOf to find all occurrences of the characters 'the' in a sentence. For example, if the sentence were "The other day I went over there", it should return 3.
我能够做到这一点,直到找到第一个索引为止,但是我不确定如何编写循环.我最初有一个for循环,用于搜索整个字符串,但它返回的是完整的字符串字符长度,而不是出现我指定的字符.我如何编写一个循环来查找单词的所有出现位置?谢谢.
I am able to do this up to the point where it finds the first index, but I'm unsure of how to write the loop. I originally had a for loop that searched the entire string, but it was returning the full string character length, instead of the occurrences of my specified character. How can I write a loop that will find all of the occurrences of the word? Thank you.
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 -----");
推荐答案
您可以跟踪索引:
int index = theString.indexOf("the");
while(index >= 0) {
index = theString.indexOf("the", index+1);
counter2++;
}
这篇关于indexOf查找字符串中单词的所有出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!