String Extraction

   

There might be occasions in your programs when you want to extract portions of a string. The String class provides this functionality with a set of methods for just that purpose. You can determine the character at a given position in the string, for example, by calling the charAt method, like this:

 String str = "This is a string"; char chr = str.charAt(6); 

In these lines, the character variable chr ends up with a value of s, which is the fifth character in the string. Why didn't chr become equal to i ? Remember that in Java, you start counting array elements at zero rather than one.

A similar method, getChars(), enables you to copy a portion of a String object to a character array:

 String str = "This is a string"; char chr[] = new char[20]; str.getChars(5, 12, chr, 0); 

In this code sample, the character array chr ends up containing the characters is a st. The getChars method's arguments are the index of the first character in the string to copy, the index of the last character in the string, the destination array, and where in the destination array to start copying characters.

The method getBytes does the same thing as getChars, but uses a byte array as the destination array:

 String str = "This is a string"; byte byt[] = new byte[20]; str.getBytes(5, 12, byt, 0); 

Another way to extract part of a string is to use the substring method:

 String str1 = "THIS IS A STRING"; String str2 = str1.substring(5); 

In this case, the String object str2 ends up equal to the substring IS A STRING. This is because substring() 's single argument is the index of the character at which the substring starts. Every character from the index to the end of the string is extracted.

Note

Remember that Strings are immutable. Therefore, all these methods that extract or otherwise seem to work on an existing String really just return a new String object and do not change the original String.


If you don't want to extract all the way to the end of the string, you can use the second version of the substring method, whose arguments specify the beginning and ending indexes:

 String str1 = "THIS IS A STRING"; String str2 = str1.substring(5, 9); 

These lines set str2 to the substring IS A.

Listing 8.3 is an application that enables you to experiment with the substring method. When you run the application, you need to provide a String and two numbers . The first number is the starting index and the second number is the ending index.

Listing 8.3 SubstringExample.java ” An Application That Extracts Substrings
 public class SubstringExample {   // Default Constructor   public SubstringExample()   {     super();   }   // Method that actually performs the extraction   public String extractSubstring( String str1, int beginIndex, int endIndex )   {     return str1.substring( beginIndex, endIndex );   }   // Main Method   public static void main( String[] args )   {     if ( args.length != 3 )     {       System.out.println(            "Usage: java StringCompareExample <String1> <String2>" ); System.exit( 0 );     }     String str = args[0];     String beginIndexStr = args[1];     String endIndexStr = args[2];     int beginIndex = 0;     int endIndex = 0;     // Make sure the arguments are valid     try     {       beginIndex = Integer.parseInt( beginIndexStr );       endIndex = Integer.parseInt( endIndexStr );     }     catch( NumberFormatException ex )     {       System.out.println( "The arguments are invalid" );     }     // Create an instance of the example     SubstringExample example = new SubstringExample();     // Get the strings passed in from the command line     // Inform the user what is going on     System.out.println(     "Extracting from string: '" + str + "'starting at: " + beginIndex + " endIndex: " + graphics/ccc.gif endIndex );     // perform the comparison     String newSubstring =          example.extractSubstring( str, beginIndex, endIndex );     System.out.println( "Substring: " + newSubstring );   } } 

Here is the output when you run the example from Listing 8.3 using some sample Strings:

 C:\jdk1.3se_book\classes>java SubstringExample "Now is the time for all" 4 15 Extrating from string: 'Now is the time for all'starting at: 4 endIndex: 15 Substring: is the time C:\jdk1.3se_book\classes> 
   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net