Java Reference
In-Depth Information
Note
If beginIndex is endIndex , substring(beginIndex, endIndex) returns an
empty string with length 0 . If beginIndex > endIndex , it would be a runtime error.
beginIndex <= endIndex
9.2.6 Converting, Replacing, and Splitting Strings
The String class provides the methods for converting, replacing, and splitting strings, as
shown in Figure 9.7.
java.lang.String
+toLowerCase(): String
+toUpperCase(): String
+trim(): String
+replace(oldChar: char,
newChar: char): String
+replaceFirst(oldString: String,
newString: String): String
+replaceAll(oldString: String,
newString: String): String
+split(delimiter: String):
String[]
Returns a new string with all characters converted to lowercase.
Returns a new string with all characters converted to uppercase.
Returns a new string with whitespace characters trimmed on both sides.
Returns a new string that replaces all matching characters in this
string with the new character.
Returns a new string that replaces the first matching substring in
this string with the new substring.
Returns a new string that replaces all matching substrings in this
string with the new substring.
Returns an array of strings consisting of the substrings split by the
delimiter.
F IGURE 9.7
The String class contains the methods for converting, replacing, and splitting strings.
Once a string is created, its contents cannot be changed. The methods toLowerCase ,
toUpperCase , trim , replace , replaceFirst , and replaceAll return a new string
derived from the original string (without changing the original string!). The toLowerCase and
toUpperCase methods return a new string by converting all the characters in the string to
lowercase or uppercase. The trim method returns a new string by eliminating whitespace
characters from both ends of the string. Several versions of the replace methods are provided
to replace a character or a substring in the string with a new character or a new substring.
For example,
returns a new string, welcome .
"Welcome". toLowerCase()
toLowerCase()
toUpperCase()
trim()
replace
replaceFirst
replace
replace
returns a new string, WELCOME .
"\t Good Night \n". trim()
"Welcome". toUpperCase()
returns a new string, Good Night .
"Welcome". replace('e', 'A')
returns a new string, WAlcomA .
"Welcome". replaceFirst("e", "AB")
returns a new string, WABlcome .
returns a new string, WABlcomAB .
"Welcome". replace("e", "AB")
returns a new string, WABcome .
"Welcome". replace("el", "AB")
The split method can be used to extract tokens from a string with the specified delimiters.
For example, the following code
split
String[] tokens = "Java#HTML#Perl" .split( "#" );
for ( int i = 0 ; i < tokens.length; i++)
System.out.print(tokens[i] + " " );
displays
Java HTML Perl
 
Search WWH ::




Custom Search