将字符串分隔出单词并计数排列
自己做了一个练习,是将一串英文句子里的每个单词分别进行计数并按少到多输出。
思路:
1.将字符串分离出来并存储到字符串数组中(String的split方法)
2.将字符串数组中的每个单词出现次数进行统计,并放入新的字符串数组中,其中下标正是其单词出现的次数,利于后面按次序排列输出
3.打印输出
直接上代码:
public static void main(String[] args) {
String text = " A##lmost every & child will complain about their parents sometimes." +
" It is natural. because when people stay together for a long time, " +
"they will start to have argument. But ignore about the unhappy time, " +
"our parents love us all the time. No matter what happen to us, " +
"they will stand by our sides. " +
"We should be grateful to them and try to understand them.";
SortTest sortTest = new SortTest();
sortTest.show(sortTest.toSum(sortTest.toWords(text)));
}
剔除非字母部分
public String[] toWords(String text) {
//剔除非大小写的字母符号并作为分隔点存储到字符串
String[] words = text.trim().split("[^a-zA-Z]+");数组中
return words;
}
统计次数
public String[] toSum(String[] words) {
String[] sorted = new String[40];
String string;
int count = 1;//记录字符串出现次数,并作为下标
for (int i = 0; i < words.length; i++) {
if (words[i].equals(".")) continue;
string = words[i];
for (int j = i + 1; j < words.length; j++) {
if (words[j].equals(words[i])) {
count++;
words[j] = ".";//为避免重复计数而设置一个非单词符
}
}
if(sorted[count]==null)sorted[count]="";//为初始赋值为空串
if (sorted[count] != ".")//如果出现相同的次数,尾随添加
{
sorted[count] = sorted[count] + " " + string;//将统计好的字符串在对应个数下标位置存储并放入字符串
}
count = 1;
}
return sorted;
}
打印输出函数
public void show(String[] sorted) {//打印输出
for (int i = 0; i < sorted.length; i++) {
if (sorted[i] != null && sorted[i] != ".") {
System.out.println(sorted[i] + " " + i);
}
}
}
输出结果
A lmost every child complain their sometimes It is natural because when people stay together for a long start have argument But ignore unhappy love all No matter what happen stand by sides We should be grateful and try understand 1
about parents they the our us them 2
will time 3
to 4
因为单词出现的次数可能会一样,导致同一下标位置要存多个字符串,我这里直接以追加的形式放在同一下标位置了,需要分开的话通过split剔除就行。初学者,或许有更有效的办法,欢迎大佬评论区指教。