Page 205 - Introduction to Programming with Java: A Problem Solving Approach
P. 205
Text Replacement
Note the replaceAll and replaceFirst methods in Figure 5.8. The replaceAll method searches its calling-object string for target, replaceAll’s first parameter. It returns a new string, in which all occurrences of target are replaced with replacement, replaceAll’s second parameter. The replaceFirst method works the same as replaceAll except that only the first occurrence of the searched-for target string is replaced. Here’s an example that illustrates both methods:4
String ladyMacBeth = "Out, damned spot! Out, I say!";
System.out.println(ladyMacBeth.replaceAll("Out", "Expunge"));
ladyMacBeth = ladyMacBeth.replaceFirst(", damned spot", "");
System.out.println(ladyMacBeth);
Update the content of the ladyMacBeth string variable.
Output:
Expunge, damned spot! Expunge, I say!
Out! Out, I say!
Note how the second statement prints the Lady MacBeth quote with both occurrences of “Out” replaced by “Expunge,” but it does not change the content of the ladyMacBeth string object. You can tell that it doesn’t change the content of the ladyMacBeth string object because the next two statements gener-
5.6 String Methods 171
ate Out!
replaceAll method does not change content of the ladyMacBeth string object is that string objects are
Out, I
say!, where “Out” is used, not “Expunge.” The reason that the second statement’s Apago PDF Enhancer
immutable. Immutable means unchangeable. String methods such as replaceAll and replaceFirst return a new string, not an updated version of the calling-object string. If you really want to change the content of a string variable, you need to assign a new string object into it. That’s what happens in the third statement where the JVM assigns the result of the replaceFirst method call into the ladyMacBeth variable.
In the Lady MacBeth example, the replaceFirst method call deletes the “damned spot” by replacing it with an empty string. Since there is only one occurrence of “damned spot,” replaceAll would yield the same result as replaceFirst. But replaceFirst is slightly more efficient and that’s why we use it here.
Whitespace Removal and Case Conversion
Note the trim, toLowerCase, and toUpperCase methods in Figure 5.8. The trim method removes all whitespace from before and after a calling-object string. The toLowerCase method returns a string iden- tical to the calling-object string except that all the characters are lowercase. The toUpperCase method re- turns an uppercase version of the calling-object string. To see how these methods work, suppose we change the previous Hamlet code to this:
String hamlet = "To be, or not to be: that is the question;";
int index = hamlet.indexOf(':');
String hamlet2 = hamlet.substring(index + 1);
System.out.println(hamlet2);
hamlet2 = hamlet2.trim();
hamlet2 = hamlet2.toUpperCase();
System.out.println(hamlet2);
4 Shakespeare, MacBeth, Act V, Sc. I.