从'a'||简化s.charAt 'b'|| 'c'||一个s.charAt

时间:2014-01-01 23:18:22

标签: java string if-statement for-loop

我正在写一个计数程序。有没有办法使用一个案例来增加字符串中字母的数量,而不是使用26个案例。有可能简化这个程序吗?

import javax.swing.JOptionPane;
public class CountLetters
{
   public static void main(String[] args)
   {
      {
      String str = JOptionPane.showInputDialog("Enter any text.");
      int count = 0;
      String s = str.toLowerCase(); 
      for (int i = 0; i < s.length(); i++) {
          if (s.charAt(i)==('a')||s.charAt(i)=='b'||s.charAt(i)=='c'||s.charAt(i)=='d'||s.charAt(i)=='e'||s.charAt(i)=='f'||
        s.charAt(i)=='g'||s.charAt(i)=='h'||s.charAt(i)=='i'||s.charAt(i)=='j'||s.charAt(i)=='k'||s.charAt(i)=='l'||
        s.charAt(i)=='m'||s.charAt(i)=='n'||s.charAt(i)=='o'||s.charAt(i)=='p'||s.charAt(i)=='q'||s.charAt(i)=='r'||
        s.charAt(i)=='s'||s.charAt(i)=='t'||s.charAt(i)=='u'||s.charAt(i)=='v'||s.charAt(i)=='w'||s.charAt(i)=='x'||
        s.charAt(i)=='y'||s.charAt(i)=='z') {
        count++;
        }
      }
      System.out.println("There are " + count + " letters in the string you entered.");
      }
   }
}   

有没有办法简化这个程序,所以只有一个if条件,而不是26?

4 个答案:

答案 0 :(得分:8)

只需使用大于和小于运算符:

if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z')

答案 1 :(得分:4)

你甚至不需要循环。

int count = str.replaceAll("[^a-zA-Z]","").length();
System.out.println("There are " + count + " letters in the string you entered.");

答案 2 :(得分:1)

您可以使用Java的Character类:

public String numLetters(String str){
    int count=0;
    for(int i=0; i<str.length(); i++){
        if(Character.isLetter(str.charAt(i))){
            count++;
        }
    }
    return count;
}

答案 3 :(得分:0)

您可以完全避免使用char并通过substring()

matches()与正则表达式一起使用
if (s.substring(i, i+1).matches("[a-z]"))

(是的,(i, i+1) ...结束索引是独占的)

编辑添加:在考虑中,

if(Character.isLowerCase(s.chatAt(i))

可能更好。使用正则表达式忽略任何性能影响,最容易阅读;有人看着它立刻明白了意图。