String Manipulation

   

Although the String class is used for string constants, the class does provide some string manipulation methods that "modify" the String object. The word modify is in quotation marks here because as stated earlier, these string manipulation methods don't actually change the original String object, but rather create an additional String object that incorporates the requested changes. A good example of this is the replace() method, which enables you to replace any character in a string with another character:

 String str1 = "THIS IS A STRING"; String str2 = str1.replace('T', 'X'); 

If the code fragment above were to be executed, str2 would contain the String XHIS IS A SXRING after execution because the call to replace requests that every occurrence of a T be replaced with an X. Note that str1 remains unchanged and that str2 is a brand new String object.

If you want to be certain of the case of characters in a string, you can rely on the toUpperCase and toLowerCase methods, each of which returns a string whose characters have been converted to the appropriate case. Look at these lines, for example:

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

After execution of this code fragment, str2 is this is a string because the toLowerCase method converts all characters in the string to lowercase. The toUpperCase method, of course, does just the opposite ”converting all characters to uppercase.

Sometimes you have strings that contain leading or trailing spaces. The String class features a method called trim that removes both leading and trailing whitespace characters. You use it like this:

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

In this example, str2 would contain the string THIS IS A STRING, missing all the spaces before the first T and after the G.

   


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