Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
TheString
class has several methods that appear to modify a string. Of course, strings can't be modified, so what these methods really do is create and return a second string that contains the result, as indicated in the following table.
Methods in the String
Class for Manipulating StringsMethod Description String concat(String)
Concatenates the String argument to the end of this string. If the length of the argument is 0, the original string object is returned. String replace(char, char)
Replaces all occurrences of the character specified as the first argument with the character specified as the second argument. If no replacements are necessary, the original string object is returned. String trim()
Removes white space from both ends of this string. String toLowerCase()
String toUpperCase()Converts this string to lower- or uppercase. If no conversions are necessary, these methods return the original string. Here's a small program,
BostonAccentDemo
, that uses thereplace
method to translate a string into the Bostonian dialect:The// This example demonstrates the use of the replace method // in the String class. public class BostonAccentDemo { private static void bostonAccent(String sentence) { char r = 'r'; char h = 'h'; String translatedSentence = sentence.replace(r, h); System.out.println(translatedSentence); } public static void main(String[] args) { String translateThis = "Park the car in Harvard yard."; bostonAccent(translateThis); } }replace
method switches all the r's to h's in thesentence
string so that the output of this program is:Pahk the cah in Hahvahd yahd.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.