How to check how many letters are in a string in java?

前端 未结 4 1639
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 18:03

How do you check how many letters are in a Java string?

How do you check what letter is in a certain position in the string (i.e, the second letter of the string)?

相关标签:
4条回答
  • 2020-12-14 18:07

    If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:

    String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // 瘌фγε                                                                    
    0 讨论(0)
  • 2020-12-14 18:15

    To answer your questions in a easy way:

        a) String.length();
        b) String.charAt(/* String index */);
    
    0 讨论(0)
  • 2020-12-14 18:24

    1) To answer your question:

      String s="Java";
      System.out.println(s.length()); 
    
    0 讨论(0)
  • 2020-12-14 18:26

    A)

    String str = "a string";
    int length = str.length( ); // length == 8
    

    http://download.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29

    edit

    If you want to count the number of a specific type of characters in a String, then a simple method is to iterate through the String checking each index against your test case.

    int charCount = 0;
    char temp;
    
    for( int i = 0; i < str.length( ); i++ )
    {
        temp = str.charAt( i );
    
        if( temp.TestCase )
            charCount++;
    }
    

    where TestCase can be isLetter( ), isDigit( ), etc.

    Or if you just want to count everything but spaces, then do a check in the if like temp != ' '

    B)

    String str = "a string";
    char atPos0 = str.charAt( 0 ); // atPos0 == 'a'
    

    http://download.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29

    0 讨论(0)
提交回复
热议问题