每个字数

时间:2019-06-09 04:51:12

标签: java regex quoting

编写一个Java程序来计算给定字符串中单词的总数,并按字母顺序打印每个单词的计数。

使用“集合”,我需要对给定字符串中的单词进行排序和打印,并按字母顺序进行限制,并按字母顺序排列相应的计数。

用双引号引起来的单词(例如“包裹”)应最后进行排序和打印。

每当我对列表进行排序时,都将首先对双引号引起来的单词进行排序(基于ACII表),但是我需要在双引号之前对所有未引用的单词进行排序。.

请帮助我找到此类排序的解决方案。

import java.util.*;

public class UniqueWord {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
           String inp = sc.nextLine();
          inp = inp.toLowerCase().replaceAll("[^a-z'\" ]"," ");
          int count=0;
          char ch[] = new char[inp.length()];
           for(int i=0; i<inp.length(); i++){
               ch[i] = inp.charAt(i);
              if(((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' '))||((ch[0]!=' ')&&(i==0))){
                  count++;
              }
           }
           System.out.println("Number of words "+count);
}

输入:

在某种意义上说,如果多个线程同时访问一个树集,并且至少有一个线程修改了该树集,则必须在外部进行同步,因此TreeSet中的实现是不同步的。这通常是通过对自然封装了该集合的某个对象进行同步来实现的。如果不存在这样的对象,则应使用Collections.synchronizedSortedSet方法“包装”该集合。

预期输出:

单词数64

带有计数的单词

a:3

访问权限:1

已完成:1

和:1

at:1

是:2

依据:1

收藏:1

当前:1

封装:1

存在:1

外部:1

如果:2

实现:1

在:2

是:2

它:1

最少:1

方法:1

修改:1

多个:1

必须:1

自然:1

否:1

不是:1

对象:2

of:1

上:1

一个:1

感觉:1

设置:4

应该:1

一些:1

例如:1

已同步:2

synchronizedsortedset:1

同步:1

那:2

the:6

此:1

线程:2

树:1

树集:1

通常:1

使用:1

“包裹”:1

编辑 得到了解决方案。...

1 个答案:

答案 0 :(得分:2)

查看此代码,根据需要进行更新。 利用集合功能,如果提供了这些功能,则避免编写代码。 尝试甚至改善以下代码。

    String input = "This is a \"long\" statement.SortedSet Collections.";

    //split string based on your delimiters ( space, comma, dot )
    String[] split = input.split("[ ,.]");
    List<String> splitData = Arrays.asList(split);

    //create the data map with num occurances
    Map<String, Integer> dataToNumOccurances = new HashMap<>();
    for (String aString : splitData) {
        int occurrences = Collections.frequency(splitData, aString);
        dataToNumOccurances.put(aString, occurrences);
    }

    //convert to list so that it could be custom sorted
    List<String> sortedWords = new ArrayList<>(dataToNumOccurances.keySet());
    sortedWords.sort(new Comparator<String>()
    {
        @Override
        public int compare(String m1, String m2)
        {
            //apply the rule to push back double quoted string
            if (m1.startsWith("\"")) {
                return m2.compareToIgnoreCase(m1);
            }
            //apply case in-sensitive sort
            return m1.compareToIgnoreCase(m2);
        }
    });


    for (String word : sortedWords) {
        System.out.println("Word: " + word + ", count: " + dataToNumOccurances.get(word));
    }