Saturday 28 June 2014

How to Extract a Character from a String in Java

This example shows how to define a string then extract the character at a given position in that string. It does this using the String.charAt() method. Note that character positions are numbered from zero, not one. The first part uses a string variable whereas the second uses a string literal:

andrew@UBUNTU:~/Java$ cat prog37.java
public class prog37
{
public static void main (String args[])
  {
  String Andrews_name = "Andrew";
  char first_letter = Andrews_name.charAt(0);
  System.out.println
   ("1st letter of Andrew = " + first_letter);
  char fourth_letter = "Andrew".charAt(3);
  System.out.println
   ("4th letter of Andrew = " + fourth_letter);
  }
}
andrew@UBUNTU:~/Java$ javac prog37.java
andrew@UBUNTU:~/Java$ java prog37
1st letter of Andrew = A
4th letter of Andrew = r
andrew@UBUNTU:~/Java$