Java Taking Strings Apart with Substrings

Java Taking Strings Apart with Substrings


You want to break a string apart into substrings by position. 


Use the String object’s substring( ) method. 


The substring( ) method constructs a new String object made up of a run of characters contained somewhere in the original string, the one whose substring( ) you called. The name of this method, substring( ), violates the stylistic dictum that words should be capitalized; if Java were 100.0% consistent, this method would be named subString. But it’s not—it’s substring. The substring method is overloaded: both forms require a starting index. The one-argument form returns from startIndex to the end. The two-argument form takes an ending index (not a length, as in some languages), so that an index can be generated by the String methods indexOf( ) or lastIndexOf( ). Note that the end index is one beyond the last character!

// File
public static void main(String[] av) {
 String a = "Java is great.";
 String b = a.substring(5); // b is the String "is great."
 String c = a.substring(5,7);// c is the String "is"
 String d = a.substring(5,a.length( ));// d is "is great."

When run, this prints the following:

> java SubStringDemo
Java is great.
is great.
is great.


Post a Comment