22

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

Kara
  • 6,115
  • 16
  • 50
  • 57
tussya
  • 359
  • 2
  • 5
  • 11
  • 6
    Is this homework? Have you tried looking at the Javadocs for the `String` class? – Cameron Skinner Aug 31 '11 at 03:08
  • 1
    Did you read the Java API doc for `String`? It details the methods that tell you its length, as well as checking the character at a position. [link for the google challenged](http://download.oracle.com/javase/7/docs/api/java/lang/String.html) – wkl Aug 31 '11 at 03:09
  • 1
    No, this isn't for homework, just a program I'm working on. – tussya Aug 31 '11 at 03:10
  • Possible duplicate of [Count letters in a string Java](http://stackoverflow.com/questions/19163876/count-letters-in-a-string-java) – Des Horsley Oct 12 '15 at 05:20

5 Answers5

48

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

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
ssell
  • 6,429
  • 2
  • 34
  • 49
7

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"; // 瘌фγε

The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc

sample.codePointCount(0, sample.length()) // returns 5

http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/

ThomasMH
  • 638
  • 1
  • 7
  • 8
5

To answer your questions in a easy way:

    a) String.length();
    b) String.charAt(/* String index */);
Alex Orzechowski
  • 377
  • 4
  • 12
  • 2
    String.length() returns the number of Unicode units, not the number of characters. The result will be correct only if every letter in a string is exactly 1 Unicode unit. – Andrei Volgin Nov 17 '16 at 19:35
0

1) To answer your question:

  String s="Java";
  System.out.println(s.length()); 
0

I could not get any of these answers to work for me using UTF-8. If you are using UTF-8, have a look at this post. I ended up using Guava's Utf8.

SedJ601
  • 12,173
  • 3
  • 41
  • 59