Pages

Thursday, May 10, 2012

The Substring Method of Java

Substring is a method/function used to select smaller strings in the String it was called on.

For example, "CatDog" is a string that contains two smaller strings, "Cat" and "Dog"
To break this "CatDog" string into the two seperate strings, "Cat" and "Dog" one would use the substring method.
Example #1:
//declaration and initialization of string1
String string1 = "CatDog";
 //prints out result of substring(2) 
System.out.println(string1.substring(2));
After running the code above you it is easy to realize we have a problem. Your console should read "tDog" which means we have not split the string1 up as we had planned. The reason is because the parameter we assigned to be 2 should have been 3. Below is the code for what we truly wanted. Goes to show that print statements are a good way to test/debug your programs!
String string1 = "CatDog";    //declaration and initialization of string1
System.out.println(string1.substring(2));    //prints result of substring(2) 
The first and only parameter in example one specified the first character of the string to start the substring from and then because there was no second integer parameter the method returned that first letter and all the characters that followed it in the string.
Example #2:
String quote = "code the gnar";
String word = quote.substring(1); 
System.out.println("original value: "+quote);
System.out.println("final value: "+word);
It is important to realize that there are more than 1 ways of calling for a substring() on a string. In the following example you will see an example using the substring(int,int) syntax. See if you can figure out what the 1st and 2nd integer paremeters are doing!
Example #3:
String alphabet = "abcdefghijklmnopqrstuvwxyz";
String letters = alphabet.substring(5,0); 
System.out.println("original value: "+alphabet);
System.out.println("final value: "+letters);

Click here to see the role of the 1st integer.
Starting index for the string

Click here to see the role of the 2nd integer.
How far after starting index to span

No comments:

Post a Comment