我找到了类似于我的问题的解决方案:
import java.util.Scanner;
public class Counter
{
public static void main ( String args[] )
{
String a = "", b = "";
Scanner s = new Scanner( System.in );
System.out.println( "Enter a string: " );
a = s.nextLine();
while ( b.length() != 1 )
{
System.out.println( "Enter a single character: " );
b = s.next();
}
int counter = 0;
for ( int i = 0; i < a.length(); i++ )
{
if ( b.equals(a.charAt( i ) +"") )
counter++;
}
System.out.println( "Number of occurrences: " + counter );
}
}
此程序仅计算所选字母出现的次数。我需要做同样的事情,但整整一个字。我将如何修改此代码以执行我需要的操作?我不是最优秀的编程人员。非常感谢您的帮助。谢谢!
答案 0 :(得分:3)
您可以使用split string
您可以将字符串拆分为空格,如
String[] words =a.split(" ");
然后像
一样循环播放for(String word : words) {
if(word.equals(testWordToCompare)
counter++;
}
}
所以你的新代码看起来像是:
import java.util.Scanner;
public class Counter
{
public static void main ( String args[] )
{
String a = "", testWordToCompare = "exist";
Scanner s = new Scanner( System.in );
System.out.println( "Enter a string: " );
a = s.nextLine();
String[] words =a.split(" ");
int counter = 0;
for(String word : words) {
if(word.equals(testWordToCompare)
counter++;
}
}
System.out.println( "Number of occurrences of " + testWordToCompare +" is : " + counter );
}
}