【问题标题】:(Java) Counting letters in a sentence?(Java)计算一个句子中的字母?
【发布时间】:2018-07-31 03:26:10
【问题描述】:

以下是我的代码:

char[] array = new char[26] ;

    int index = 0 ;
    int letter = 0 ;
    int countA = 0 ;

    String sentence = "Once upon a time..." ;

    if(sentence.contains("."))
    {
        String sentenceNoSpace = sentence.replace(" ", "").toLowerCase() ;
        String sentenceFinal = sentenceNoSpace.substring(0, sentenceNoSpace.indexOf(".")) ;
        char[] count = new char[sentenceFinal.length()] ;
        for (char c = 'a'; c <= 'z'; c++) 
        {
            array[index++] = c ;
            for(int i = 0; i < sentenceFinal.length(); i++)
            {
                if(sentenceFinal.charAt(i) == c)
                    count[letter++] = c ; 
                //if(sentenceFinal.charAt(i) == 'a')    
                    //countA++ ;   
            }

        }
        String result = new String(count) ; // Convert to a string.
        System.out.println("\n" + result) ;

        System.out.println("\nTotal number of letters is " + result.length()) ;
        System.out.println(countA) ;
    }
    else
    {
       System.out.println("You forgot a period. Try again.") ;
    }

我无法计算给定句子中有多少个 a、b、c 等。我有一种方法可以做到,这就是这部分

//if(sentenceFinal.charAt(i) == 'a')    
                //countA++ ;

我可以一直创建到 z。有没有更有效的方法?

注意:不要使用 Hashmap 或任何其他高级技术。

【问题讨论】:

    标签: java arrays char counting


    【解决方案1】:

    没有必要消除空格。这只是您正在做的额外工作。

    int countOfLetters = 0 ;
    String sentence = "Once upon a time..." ;
    sentence = sentence.toLowerCase();
    int[] countOfAlphabets = new int[26];
    for (int i = 0; i < sentence.length(); i++) {
        if (sentence.charAt(i) >= 'a' && sentence.charAt(i) <= 'z') {
            countOfAlphabets[sentence.charAt(i) - 97]++;
            countOfLetters++;
        }
    }
    

    所以,countOfLetters 会给你字母的总数。 如果您想要个人计数,例如,假设您想要计数 'c',

    您可以通过访问countOfAlphabets 数组来获取它,例如countOfAlphabets['c' - 97](97 是 'a' 的 ASCII 值)

    【讨论】:

      【解决方案2】:

      使用int 数组letterCounts 来存储每个字母的计数。假设字母的大小写可以忽略,letterCounts数组的长度为26。

      遍历字符串的字符并更新数组中对应的整数。使用其 ASCII 值查找对应的索引,如下所示。

      letterCounts[c - 97]++

      97 是 'a' 的 ASCII 值,其计数需要存储在索引 0 处。

      这样,从字符的 ASCII 值中减去 97 将得到该字符的相应索引。

      注意:这是假设您要存储小写字母的计数。

      【讨论】:

        【解决方案3】:

        不使用地图相当繁琐,但这将计算字符串中的所有字符。

        您可能需要修改以排除空格等内容。

        public class Main {
        
            public static void main(String[] args) {
                String sentence = "Once upon a time...";
        
                // Create an array of size 256 ASCII_SIZE
                int count[] = new int[256];
                int length = sentence.length();
        
                // Initialize count array index
                for (int i = 0; i < length; i++)
                    count[sentence.charAt(i)]++;
        
                // Create an array of given String size
                char chars[] = new char[sentence.length()];
                for (int i = 0; i < length; i++) {
                    chars[i] = sentence.charAt(i);
                    int find = 0;
                    for (int j = 0; j <= i; j++) {
        
                        // If any matches found
                        if (sentence.charAt(i) == chars[j])
                            find++;
                    }
        
                    if (find == 1) {
                       System.out.println("Occurrence of " + sentence.charAt(i) + " is:" + count[sentence.charAt(i)]);
        
                    }
                }
            }
        }
        

        哪些输出:

        Occurrence of O is:1
        Occurrence of n is:2
        Occurrence of c is:1
        Occurrence of e is:2
        Occurrence of   is:3
        Occurrence of u is:1
        Occurrence of p is:1
        Occurrence of o is:1
        Occurrence of a is:1
        Occurrence of t is:1
        Occurrence of i is:1
        Occurrence of m is:1
        Occurrence of . is:3
        

        【讨论】:

          【解决方案4】:

          检查下面的代码你可以有一个 26 长度的数组,索引将根据字母的存在而增加。

          public void getResult(){
          
                  int [] charCount = new int [26];
                  int countA = 0 ;
          
                  String sentence = "Once upon a time..." ;
          
                  if(sentence.contains("."))
                  {
                      String sentenceNoSpace = sentence.replace(" ", "").toLowerCase() ;
                      String sentenceFinal = sentenceNoSpace.substring(0, sentenceNoSpace.indexOf(".")) ;
          
                      char[] sentenceCharArray = sentenceFinal.toCharArray();
                      //char a = 97;
                      for (int i = 0; i <sentenceCharArray.length ; i++) {
                          int index = sentenceCharArray[i] - 97 ;
                          if(index >= 0 && index <= 26) {
                              charCount[index] += 1;
                          }
                      }
          
          
                      System.out.print("Result : ");
          
                      for (int i = 0; i < charCount.length ; i++) {
                          System.out.print(charCount [i]+" , ");
                      }
          
          
                      System.out.println("\nTotal number of letters is " + sentenceCharArray.length) ;
                  }
                  else
                  {
                      System.out.println("You forgot a period. Try again.") ;
                  }
              }
          

          【讨论】:

            【解决方案5】:

            由于美国字母表中有 26 个字母,您可以使用大小为 26 的 int[]

            int[] letterCount = new int[26];

            保存每个字母的计数,其中索引 0 代表“a”,1 代表“b”,等等...

            当您遍历句子时,检查您所在的字符是否为字母Character.isLetter(),然后递增数组中表示该字母的元素。

            letterCount[letter - 'a']++;
            

            我们从字母中减去“a”,得到正确的索引。

            代码示例

            package stackoverflow;
            
            public class Question {
            
                public static void main(String[] args) {
                    String sentence = "The quick brown fox jumps over the lazy dog.";
                    int[] letterCount = new int[26];
                    if (sentence.contains(".")) {
                        // toLowerCase() the sentence since we count upper and lowercase as the same
                        for (char letter : sentence.toLowerCase().toCharArray()) {
                            if (Character.isLetter(letter)) {
                                letterCount[letter - 'a']++;
                            }
                        }
            
                        // Display the count of each letter that was found
                        int sumOfLetters = 0;
                        for (int i = 0; i < letterCount.length; i++) {
                            int count = letterCount[i];
                            if (count > 0) {
                                System.out.println((char)(i + 'a') + " occurs " + count + " times");
                                sumOfLetters += count;
                            }
                        }
            
                        System.out.println("Total number of letters is " + sumOfLetters);
                    } else {
                        System.out.println("You forgot a period.  Try again.");
                    }
                }
            }
            

            结果

            a occurs 1 times
            b occurs 1 times
            c occurs 1 times
            d occurs 1 times
            e occurs 3 times
            f occurs 1 times
            g occurs 1 times
            h occurs 2 times
            i occurs 1 times
            j occurs 1 times
            k occurs 1 times
            l occurs 1 times
            m occurs 1 times
            n occurs 1 times
            o occurs 4 times
            p occurs 1 times
            q occurs 1 times
            r occurs 2 times
            s occurs 1 times
            t occurs 2 times
            u occurs 2 times
            v occurs 1 times
            w occurs 1 times
            x occurs 1 times
            y occurs 1 times
            z occurs 1 times
            Total number of letters is 35
            

            反驳问题

            使用 Java 8 和使用 chars()String 有什么问题?有了它,你可以用更少的代码完成同样的事情。对于字母总数,我们只使用String.replaceAll() 并从String 中删除所有具有[^A-Za-z] 模式的非字母并使用结果的length()

            package stackoverflow;
            
            import java.util.function.Function;
            import java.util.stream.Collectors;
            
            public class Question {
            
                public static void main(String[] args) {
                    String sentence = "The quick brown fox jumps over the lazy dog.";
            
                    System.out.println(sentence.toLowerCase().chars()
                        // Change the IntStream to a stream of Characters
                        .mapToObj(c -> (char)c)
                        // Filter out non lower case letters
                        .filter(c -> 'a' <= c && c <= 'z')
                        // Collect up the letters and count them
                        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())));
            
                    System.out.println("Total letter count is " + sentence.replaceAll("[^A-Za-z]", "").length());               
                }
            }
            

            结果

            {a=1, b=1, c=1, d=1, e=3, f=1, g=1, h=2, i=1, j=1, k=1, l=1, m=1, n=1, o=4, p=1, q=1, r=2, s=1, t=2, u=2, v=1, w=1, x=1, y=1, z=1}
            Total letter count is 35
            

            【讨论】:

              【解决方案6】:

              如果Regex 不被视为高科技,你可以用正则表达式解决它?

              思路很简单:去掉所有字母,从原始字符串长度中减去输出得到计数器

              String sentence = "Once upon a time...";
              String noLetterString = sentence.replaceAll("[a-zA-Z]", "");
              int counterLetter = sentence.length() - noLetterString.length();
              System.out.println("counter:" + counterLetter);
              

              通过老派编程? 这里的想法是相反的,只附加字母

              String sentence = "Once upon a time...";
              String lowerCase = sentence.toLowerCase(); // to avoid comparison to UpperCase letters
              StringBuilder counterStr = new StringBuilder();
              for (char l : lowerCase.toCharArray()) {
                  if (l >= 'a' && l <= 'z') {
                      counterStr.append(l);
                  }
              }
              
              System.out.println("counterStr:" + counterStr);
              System.out.println("counter:" + counterStr.length());
              

              【讨论】:

                【解决方案7】:

                这里是更新代码:

                int[] array = new int[26] ;
                
                    String sentence = "Once upon a time..." ;
                
                    if(sentence.contains("."))
                    {
                        String sentenceNoSpace = sentence.replace(" ", "").toLowerCase() ;
                        String sentenceFinal = sentenceNoSpace.substring(0, sentenceNoSpace.indexOf(".")) ;
                
                        for (char c : sentenceFinal.toCharArray()) 
                        {
                            System.out.println(c+"  "+(c-97)); 
                            array[c-97] += 1;     
                        }
                
                      // System.out.println("\n" + Arrays.toString(array)) ;
                
                        for(int i=0; i< array.length;i++) {
                
                            if(array[i] != 0) {
                
                            char c = (char)(i+97);
                            System.out.println(c+" occured "+ array[i]+" times");
                          }
                        }
                    }
                    else
                    {
                       System.out.println("You forgot a period. Try again.") ;
                    }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2015-10-08
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-02-16
                  • 1970-01-01
                  • 2016-05-18
                  • 2023-04-03
                  • 2022-09-23
                  相关资源
                  最近更新 更多