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


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)?

This question is tagged with java string

~ Asked on 2011-08-31 03:07:25

The Best Answer is



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


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 )

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 != ' '


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

~ Answered on 2011-08-31 03:10:53


To answer your questions in a easy way:

    a) String.length();
    b) String.charAt(/* String index */);

~ Answered on 2012-12-20 00:23:51

Most Viewed Questions: