Thursday, 15 January 2015

Java Strings - find the location of a character in a string

Java is a very powerful tool especially  when dealing with Strings. Today we will look at a very simple program related to strings in Java. Lets say we want to write a program which store a string in a variable and print it.

public class StringExample{

    public static void main(String[] args){

       String st = "John Doe";
       System.out.println(st);
    }

}

The above program will create a variable called st and the value of the variable is John Doe. So the println statement will output John Doe because it is the value contained in st.

There are a number of items we can perform on a string object that we can also output, for example:

-count the alphabets
-check the letter at a particular location
-check for only upper case letters
-check for only lower case letters etc

so for example , let us modify the program so that we check the letter at position 2. the alphabets are numbered beginning with index 0, so at index 0 we have J, index 1 we have o, index 2 we have h..and so on...so we are expecting our program to output 'h'as our result so this is what we do:

public class StringExample{

 public static void main(String[] args){

        String st = "John Doe";

      System.out.println(st.charAt(2));
      }

}

the method called charAt(int index) is used to find the character at a location specified in the parameter location. This will return a character and since we have called it in the println statement, the character will be  output to the console.
Copy this code and try to find the location of different characters and different indexes. You can also change the string itself and iterate though the string to find the location of different characters.

That is all for now next time we continue with more string manipulations