gpt4 book ai didi

java - 如何计算字符串数组中字符串的重复次数

转载 作者:行者123 更新时间:2023-12-01 21:49:00 25 4
gpt4 key购买 nike

我正在尝试计算一个单词在标准输入中重复的次数。

输入示例:

This is a test, this is is

期望的输出:

this 2
is 3
a 1
test 1

我有一个 int[] 来存储 wordCount 但我不确定在哪里使用它,int 计数只是临时的,以便程序可以运行。

这是我的引用代码:

import java.util.Scanner;
public class WCount {

public static void main (String[] args) {

Scanner stdin = new Scanner(System.in);

String [] wordArray = new String [10000];
int [] wordCount = new int [10000];
int numWords = 0;

while(stdin.hasNextLine()){
String s = stdin.nextLine();
String [] words = s.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\\
s+"); //stores strings as words after converting to lowercase and getting rid of punctuation
for(int i = 0; i < words.length; i++){
int count = 0; //temporary so program can run
for(int j = 0; j < words.length; j++){
if( words[i] == words[j] )
count++;
System.out.println("word count: → " + words[i] + " " + count);
}
}

}

最佳答案

我会使用这样的东西:

import java.util.ArrayList;
import java.util.Scanner;

public class WCount {

public static void main(String[] args) {

Scanner stdin = new Scanner(System.in);

String[] wordArray = new String[10000];
int[] wordCount = new int[10000];
int numWords = 0;

while (stdin.hasNextLine()) {
String s = stdin.nextLine();
ArrayList<String> noDuplicated = new ArrayList<String>();
String[] words = s.replaceAll("[^a-zA-Z ]", "").toLowerCase()
.split("\\s+"); // stores strings as words after converting
// to lowercase and getting rid of
// punctuation

//Array that contains the words without the duplicates ones
for (int i = 0; i < words.length; i++) {
if(!noDuplicated.contains(words[i]))
noDuplicated.add(words[i]);
}

//Count and print the words
for(int i=0; i<noDuplicated.size();i++){
int count = 0;
for (int j = 0; j < words.length; j++) {
if (noDuplicated.get(i).equals(words[j]))
count++;
}
System.out.println("word count: → " + words[i] + " "
+ count);
}

}
}
}

输出:

This is a test, this is is
word count: → this 2
word count: → is 3
word count: → a 1
word count: → test 1

希望有用!

关于java - 如何计算字符串数组中字符串的重复次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35474887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com