Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 640
tussya Avatar asked Aug 31 '11 03:08

tussya


People also ask

How do you count letters in a string in Java?

String str = "9as78"; Now loop through the length of this string and use the Character. isLetter() method. Within that, use the charAt() method to check for each character/ number in the string.

How many characters are in a string Java?

String length limit: The maximum length a string can have is: 231-1.

How many times a letter appears in a string Java?

Let's start with a simple/naive approach: String someString = "elephant"; char someChar = 'e'; int count = 0; for (int i = 0; i < someString. length(); i++) { if (someString. charAt(i) == someChar) { count++; } } assertEquals(2, count);


1 Answers

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

like image 103
ssell Avatar answered Oct 20 '22 13:10

ssell