首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算字符串中的单词数

计算字符串中的单词数
EN

Stack Overflow用户
提问于 2016-11-09 11:15:50
回答 3查看 1.2K关注 0票数 1

我应该创建一个方法来计算句子中达到或超过int minLength的单词的数量。例如,如果给定的最小长度是4,您的程序应该只计算长度至少为4个字母的单词。

单词can将由一个或多个空格分隔。非字母字符(空格、标点、数字等)可能存在,但它们不计入单词的长度。

代码语言:javascript
复制
    public static int countWords(String original, int minLength) {
    original = original.replaceAll("[^A-Za-z\\s]", "").replaceAll("[0-9]", "");
    String[] words = original.split("\\s+");


    for(String word : words){ System.out.println(word); }

    int count = 0;
    for (int i = 0; i < words.length; i++) {
        if (words[i].length() >= minLength) {
            count++;
        } else if (words[i].length() < minLength || minLength == 0) {
            count = 0;
        }
    }
    System.out.println("Number of words in sentence: " + count);
    return count;
}

好吧,我改变了我的代码,但是现在计数器减少了一分。我这样说:西班牙是一个美丽的国家;那里的胡子温暖、沙质、一尘不染。“

我收到的输出是...西班牙是一个美丽的国家,那里的海滩温暖、多沙、一尘不染。

单词的数量减少了1,应该是11。看起来它没有计算句子中的最后一个单词。我不确定问题的根源在哪里,因为我只更改了replaceAll以包含转义字符。

EN

回答 3

Stack Overflow用户

发布于 2016-11-09 11:46:55

1)按空格拆分

2)修剪以删除多余的空格,并将所有奇怪的内容替换为"“(删除)

3)用更多或等于你的minLength来计算单词

示例:

代码语言:javascript
复制
public class TesterClass
{
    public static void main (String args [])
    {
            String original = ",,, hello$hello asdasda ddd 33d   3333d        a";
            int minLength = 3;
            String[] words = original.split(" ");
            int count=0;

            for( String trimAndNoStrange : words)
            {
                String fixed = trimAndNoStrange.trim ( ).replaceAll("[^A-Za-z]", "").replaceAll("[0-9]", "");
                if(fixed.length ( ) >= minLength)
                {
                    count++;
                }
            }


            System.out.println("Number of words in sentence: " + count);

        }

}

输入/输出示例:

输入:",,,hello$hello asdasda ddd 33d 3333d a“

输入: minLength = 3;

输出:句子中的单词数: 3

票数 0
EN

Stack Overflow用户

发布于 2016-11-09 11:58:11

尝试将代码更新为以下代码

代码语言:javascript
复制
original = original.replaceAll("[^A-Za-z\\s]", "").replaceAll("[0-9]", "");

  • 替换为空字符串而不是空格
  • 允许空格存在(将\s添加到正则表达式中)
票数 0
EN

Stack Overflow用户

发布于 2016-11-10 01:18:35

你应该专注于你想做的事情,而不是从相反的方面偷偷地绕过你的目标。你想要计算单词,所以只需这样做,而不是替换或拆分。

一个障碍可能是你对“word”的特殊定义,但花一些时间思考合适的模式是值得的,它将比花时间考虑多个替换模式加上一个拆分模式更有回报。

忽略长度限制,单词是以字母开头的任何内容(数字和分隔符无论如何都不会在最后的任务中计算在内),后跟任意数量的非空格字符:

代码语言:javascript
复制
String s
    ="Spain is a beautiful country; the beache's are warm, sandy and spotlessly clean.";
int count=0;
for(Matcher m=Pattern.compile("[A-Za-z][^\\s]*").matcher(s); m.find();) {
    System.out.println(count+": "+m.group());
    count++;
}
System.out.println("total number of words: "+count);

将打印:

代码语言:javascript
复制
0: Spain
1: is
2: a
3: beautiful
4: country;
5: the
6: beache's
7: are
8: warm,
9: sandy
10: and
11: spotlessly
12: clean.
total number of words: 13

合并最小长度,不计算非字母字符,可能有点棘手,但可以通过考虑每个字母后面可能有任意数量的可忽略(即非字母非空格)字符来解决,我们只计算该组合的出现次数。所以

代码语言:javascript
复制
String s
    ="Spain is a beautiful country; the beache's are warm, sandy and spotlessly clean.";
int count=0;
for(Matcher m=Pattern.compile("([A-Za-z][^A-Za-z\\s]*+){4,}").matcher(s); m.find();) {
    System.out.println(count+": "+m.group());
    count++;
}
System.out.println("total number of words >=4 letters: "+count);

打印

代码语言:javascript
复制
0: Spain
1: beautiful
2: country;
3: beache's
4: warm,
5: sandy
6: spotlessly
7: clean.
total number of words >=4 letters: 8

如果您想知道,*+量词类似于*,但它告诉正则表达式引擎不要在匹配的该部分中进行回溯,这在此上下文中是一种优化。简单地说,如果可以忽略的字符后面没有字母,那么在可以忽略的字符中也不会有字母,所以引擎不应该花时间去寻找一个字母。

将其带入方法形式:

代码语言:javascript
复制
public static int countWords(String original, int minLength) {
    if(minLength<1) throw new IllegalArgumentException();
    int count=0;
    for(Matcher m=Pattern.compile("([A-Za-z][^A-Za-z\\s]*+){"+minLength+",}")
                         .matcher(original); m.find();) {
        count++;
    }
    return count;
}

并像这样使用它

代码语言:javascript
复制
String s
    ="Spain is a beautiful country; the beache's are warm, sandy and spotlessly clean.";
for(int i=1; i<10; i++)
    System.out.println("with at least "+i+" letters: "+countWords(s, i));

收益率

代码语言:javascript
复制
with at least 1 letters: 13
with at least 2 letters: 12
with at least 3 letters: 11
with at least 4 letters: 8
with at least 5 letters: 7
with at least 6 letters: 4
with at least 7 letters: 4
with at least 8 letters: 2
with at least 9 letters: 2
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40499752

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档