【发布时间】:2016-12-01 21:23:53
【问题描述】:
我正在尝试使用 indexOf 来查找句子中所有出现的字符“the”。例如,如果句子是“The other day I went over there”,它应该返回 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 -----");
【问题讨论】:
-
我建议使用正则表达式进行搜索。
-
您介意解释一下您所说的正则表达式是什么意思吗?
-
重复问题,该问题之前在this post中回答过