Converting, Replacing and Splitting Strings
The String class provides the methods for converting, replacing and splitting strings as given in table.
java.lang.String
Method syntax | Return type | Description |
---|---|---|
+toLowerCase() | String | Returns a new string with all characters converted to lowercase |
+toUpperCase() | String | Returns a new string with all characters converted to uppercase |
+trim() | String | Returns a new string with blank characters trimmed on both sides |
+replace(oldChar:char, newChar:char) | String | Returns a new string that replaces all matching characters in this string with the new character |
+replaceFirst(oldString:String, newString:String) | String | Returns a new string that replaces the first matching substring in this string with the new substring |
+replaceAll(oldString:String, newString:String) | String | Returns a new string that replaces all matching substrings in this string with the new substring |
+split(delimeter:String) | String[] | Returns an array of strings consisting of the substrings split by the delimiter |
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 mehtod return a new string by converting all the characters in the string to lowercase or uppercase. The trim method retruns a new string by eliminating blank 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.