Tuesday, March 1, 2011

Get the character at a certain position in a string in Java

Assume that you want to get the 2nd character of the text "My Text". Then you can get the second character as below.
String txt = "My Text";
System.out.println(txt.charAt(1));//Remember that the index is zero based.

If you want to get the last character as a char, use the following method.
String txt = "My Text";
char lastChar = txt.charAt(txt.length() - 1);
System.out.println(lastChar);


If you want to get the last character as a String, use the following method.
String last = txt.substring(txt.length()-1);
System.out.println(last);

No comments:

Post a Comment