如何计算和排序字符串中的字母

时间:2016-08-12 08:05:32

标签: java

我想对用户输入的字母进行排序,并打印出来自用户的字符串中每个字母的数量。这是我到目前为止,我想知道这是否是正确的方法。我对java比较新,所以请尽可能保持简单。根据我使用循环而不是大量if else结构的建议,我对我的代码做了一些调整。这就是我所拥有的:

public class Assignment9
{
public static void main( String [] args )
{
    String user_string = Input.getString( "Please enter a string" );
    int length = user_string.length();
    int char_number = 1;
    int alphabet[] = new int[26];
    for( int repeats = 0 , repeats <= length , repeats++ )
    {
        char letter = user_string.charAt( char_number );
        char to_be_tested = Character.toLowerCase( letter );
        int subscript = 0;
        for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
        {
            char tester = (char) letter_number;

            if( to_be_tested == tester )
            {
                alphabet[subscript]++;
                subscript++;
            }
        }
        char_number++;
    }
    display( alphabet );
}
public static void display( int alphabet[] )
{
    int letter = 65;
    for( int a = 0; a < alphabet.length; a++ )
    {
        char character = ( char )letter;
        System.out.println ( "letter " + character + " count is " + alphabet[a] );
        letter++;
    }
}
}

我收到了这些错误

Compilation errors

test.java:9: error: ';' expected
            for( int repeats = 0 , repeats <= length , repeats++ )
                                          ^
test.java:9: error: illegal start of expression
            for( int repeats = 0 , repeats <= length , repeats++ )
                                           ^
test.java:9: error: ';' expected
            for( int repeats = 0 , repeats <= length , repeats++ )
                                             ^
test.java:9: error: illegal start of expression
            for( int repeats = 0 , repeats <= length , repeats++ )
                                                     ^
test.java:9: error: ')' expected
            for( int repeats = 0 , repeats <= length , repeats++ )
                                                      ^
test.java:9: error: illegal start of expression
            for( int repeats = 0 , repeats <= length , repeats++ )
                                                                 ^
test.java:14: error: ';' expected
                    for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
                                                              ^
test.java:14: error: illegal start of expression
                    for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
                                                               ^
test.java:14: error: ';' expected
                    for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
                                                                 ^
test.java:14: error: illegal start of expression
                    for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
                                                                      ^
test.java:14: error: ')' expected
                    for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
                                                                       ^
test.java:14: error: illegal start of expression
                    for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
                                                                                        ^
12 errors

5 个答案:

答案 0 :(得分:2)

这是一种计算字母的简单方法,忽略大小写:

final int[] chars = new int[26];
for (char c : value.toLowerCase().toCharArray()) {
  if ((c >= 'a') && (c<= 'z')) {
     chars[c - 'a']++;
  }
}

演示:https://repl.it/CmYR/0

答案 1 :(得分:2)

事情是 正在做所有的工作。您需要做的是使 计算机 工作。所有这些打印声明都没有充分的理由进行大量的复制粘贴。因此,使用循环是一种更有效的方法。既然你已经知道了循环,你就可以提出这个解决方案 -

import java.io.*;

public class experiments {
public static void main(String[] args) throws IOException {

    //Scanner sc=new Scanner(System.in);
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

    int i,j;
    char chr;
    int len,count=0;
    System.out.println("Enter text-->");
    String str=br.readLine();
    str=str.toUpperCase();
    len=str.length();
    for(i='A';i<='Z';i++)
    {
        for(j=0;j<len;j++)
        {
            chr=str.charAt(j);
            if(chr==i)count++;              
        }
        System.out.println((char)i+"-->"+count);
        count=0;
    }
  }
}

答案 2 :(得分:1)

更简单的方法是使用地图数据结构。它存储(键,值)对。在您的情况下,键将是字母,值将是表示计数的整数。所以,当你遇到说,一个&#39; a&#39;您执行yourMap.get('a')并增加与该键配对的值。

在这里,您可以阅读java中的地图:https://docs.oracle.com/javase/7/docs/api/java/util/Map.html

答案 3 :(得分:1)

我宁愿在这里使用地图来存储每个字母的数量:

Map<Character, Integer> letterMap = new HashMap<>();
String userString = Input.getString( "Please enter a string" );

for (int i=0; i < userString.length(); ++i) {
    char letter = userString.charAt(i);
    Integer value = letterMap.get(letter);

    letterMap.put(letter, value == null ? 1 : value.intValue() + 1);
}

for (Map.Entry<Character, Integer> entry : letterMap.entrySet()) {
    System.out.println("Letter '" + entry.getKey() + "' appeared " + entry.getValue() + " times.");
}

正如@Stephank指出的那样,此解决方案不会打印输入中根本不显示的字母的任何摘要统计信息。如果您要打印所有字母的统计信息,即使它们没有显示,您也可以使用以下代码为地图播种:

for (char letter = 'a'; letter <= 'z'; ++letter) {
    letterMap.put(letter, 0);
}

答案 4 :(得分:0)

使用Java 8 Streams

    String data = "some letters to count";

    Stream.of(data.split("(?!^)"))
          .collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()))
          .forEach((key, value)->System.out.println(key+": "+value));

以下是解释:

  1. 首先,我们使用正则表达式将数据拆分为一个字母字符串:data.split("(?!^)");我们获得了一个String&#39>的数组。

    0 = "s" 1 = "o" 2 = "m" 3 = "e" 4 = " " 5 = "l" 6 = "e" 7 = "t" 8 = "t" 9 = "e" 10 = "r" 11 = "s" 12 = " " 13 = "t" 14 = "o" 15 = " " 16 = "c" 17 = "o" 18 = "u" 19 = "n" 20 = "t"

  2. 我们从上述数组创建StreamStream.of(data.split("(?!^)"))

  3. 我们使用groupingBy Collector执行此步骤中的所有排序和计数,并传递TreeMapSortedMap一个将保留MapEntry的实现按键排序):.collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()))

    此步骤的结果是排序TreeMap,其中单独的字符String作为键,并且此字符的计数为值。

    0 = {TreeMap$Entry@755} " " -> "3" 1 = {TreeMap$Entry@756} "c" -> "1" 2 = {TreeMap$Entry@757} "e" -> "3" 3 = {TreeMap$Entry@758} "l" -> "1" 4 = {TreeMap$Entry@759} "m" -> "1" 5 = {TreeMap$Entry@760} "n" -> "1" 6 = {TreeMap$Entry@761} "o" -> "3" 7 = {TreeMap$Entry@762} "r" -> "1" 8 = {TreeMap$Entry@763} "s" -> "2" 9 = {TreeMap$Entry@764} "t" -> "4" 10 = {TreeMap$Entry@765} "u" -> "1"

  4. 最后,我们打印结果:.forEach((key, value)->System.out.println(key+": "+value));