[英]Word count java
So my code is supposed to return the amount of words (words being lengths of letters) and it works except for when i enter anything 0 or less can some pplease help spot the error??所以我的代码应该返回单词的数量(单词是字母的长度)并且它可以工作,除了当我输入 0 或更少的任何东西时,请帮助发现错误?
Edited Code:编辑代码:
public class WordCount {
public static int countWords(String original, int minLength){
String[] s1 = original.split("\\s+");
for(int i = 0; i < s1.length; i++){
s1[i] = s1[i].replaceAll("^\\W]", "");
}
int count = 0;
for(int i = 0; i < s1.length; i++){
String str = s1[i];
int len = 0;
for(int x = 0; x < str.length(); x++){
char c = str.charAt(x);
if(Character.isLetter(c) == true){
len ++;
}
}
if(len >= minLength){
count ++;
}
}
return count;
}
public static void main(String[] args){
System.out.println("enter string: ");
String s = IO.readString();
System.out.println("min length: ");
int m = IO.readInt();
System.out.println(countWords(s, m));
}
}
Try this :尝试这个 :
String s = original.replaceAll("[\\W]", " ").replaceAll("[\\s]+", " ");
because you have to replace spaces more than 1 here as well.因为你也必须在这里替换超过 1 的空格。
I would apply a solution that uses a regular expression to process the text.我会应用一个使用正则表达式来处理文本的解决方案。
I prepared a sketch of code, which can be summarized as follows:我准备了一个代码草图,可以总结如下:
String[] words = myString.replaceAll("[^a-zA-Z ]", " ").split("\\s+");
What this code does is to:这段代码的作用是:
The resulting array words
contains all the words (ie, sequences of letters) which were contained in the original string.结果数组words
包含原始字符串中包含的所有单词(即字母序列)。
A full example can be found here .一个完整的例子可以在这里找到。 In this example I just print the words as a list.在这个例子中,我只是将单词打印为列表。 In case you want just the count of words, you just have to return the count of elements in the array.如果您只想要单词的数量,您只需返回数组中元素的数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.