【问题标题】:How to count the number of each word in string [closed]如何计算字符串中每个单词的数量[关闭]
【发布时间】:2016-08-25 23:16:22
【问题描述】:

我正在尝试查找字符串中每个单词的出现次数。

例如Sentence=" My home, is my home"。答案是“我的”=2; “家”=2; “是”=1

这是我的代码:

int count;
count = 0;
String text[] = new String[100];
String Temp[] = new String[100];
text = Text.getText().split("\\W");
Temp = Text.getText().split("\\W");
for (int j = 0;  j < text.length; j++) {
    for (int i = 0; i < text.length; i++) {

        if (text[j].equals(Temp[i])) {
            count += 1;
            System.out.println(text[i] + "-" + count);
        }
    }
}

输入:me.me.me.me 输出:

me-1
me-2
me-3
me-4
me-5
me-6
me-7
me-8
me-9
me-10
me-11
me-12
me-13
me-14
me-15
me-16

【问题讨论】:

  • 您可以使用 HashMap 轻松完成。看看我的回答。并且不要忘记通过单击答案旁边的空心勾号将其标记为accepted。 ;-)
  • 这个地方不适合问作业问题。

标签: java


【解决方案1】:

您可以使用 split() 拆分字符串

String[] s;
s = split("."); //Will split a sentence into an array

所以如果输入是 me.me.me.me。 S[0] =“我”,S[1] =“我”等

然后你只需找到数组的长度就可以查看原始字符串中有多少个单词。 所以.....

count = s.length;
System.out.println(count);

您提出的问题非常复杂,但我假设您正在尝试“计算字符串中的单词数。 我还不能发表评论,因为我的代表开始了。但是,您已经有了一个可行的解决方案......这不是将解决方案发布到您自己的答案以炫耀它的地方吗?

【讨论】:

  • 我需要计算句子中每个单词的数量。例如 Sentence="我的家,就是我的家"。答案是“我的”=2; “家”=2; “是”=1;
【解决方案2】:

您可以使用HashMap、HashMap&lt;String, Integer&gt; 来执行此操作。

HashMap<String, Integer> map = new HashMap<>();
String sentence = "My home, is my home".toLowerCase();

for(String word : sentence.split("\\W")) {
    if(word.isEmpty()) {
        continue;
    }
    if(map.containsKey(word)) {
        map.put(word, map.get(word)+1);
    }
    else {
        map.put(word, 1);
    }
}

for(Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

输出:

is: 1
my: 2
home: 2

看看这个SO post。在那里,您会看到与您所要求的回答非常相似的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 2021-04-28
    相关资源
    最近更新 更多