程序要求输入字符串,然后输入最小字长。 如果单词小于最小单词长度,则不计算在内。 我试图在不使用 split() 或任何其他帖子所说的解决这些问题的情况下执行该程序。
我想也许我必须检查第一个单词、最后一个单词,然后检查中间的单词。但我有麻烦了。我在这上面花了太长时间,但我无法弄清楚。
IO 是一个不同的类,用于输入、输出等。
public class WordCount {
public static void main(String[] args) {
int minLength;
System.out.println("Enter a string.");
String string=IO.readString();
String str1=string.toLowerCase(); //changes all characters in the string to lower case
String str=str1.trim(); //Trims all spaces in the end.
System.out.println("Enter minimum length for each word.");
minLength=IO.readInt();
int num=wordCount(str, minLength);
IO.outputIntAnswer(num);
}
public static int wordCount(String str, int minLength){ //Method that counts words.
int count=0;
// First Word
for(int i=0;i<str.length();i++){
if (str.charAt(i)==' '){
String firstWord=str.substring(0,i);
if (firstWord.length()>=minLength){
count++;
}
}
}
// Last Word
for (int i=str.length()-1;i>0;i--){
if(str.charAt(i)==' '){
String lastWord=str.substring(i, str.length()-1);
if(lastWord.length()>=minLength){
count++;
}
for (int j=0; j<i;j++){ //An attempt to find other words in between..does not work
if(str.charAt(j)==' '){
String word=str.substring(j+1, str.indexOf(' ', j+1));
if(word.length()>=minLength){
count++;
}
}
}
}
}
return count;
}
}
最佳答案
这应该足够了:
public static int wordCount(String str, int min) {
int count = 0;
str = str.trim()+" ";
for(int i=0, st=0; i<str.length(); i++) {
if(str.charAt(i) != ' ') continue;
if(i-st >= min) count++;
st = i+1;
}
return count;
}
关于Java计算字符串中的单词数,而不使用split或StringTokenizers等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29461255/