Java Reference
In-Depth Information
Note that the trim() method removes only leading and trailing whitespaces. It does not remove any whitespace
or control characters if they appear in the middle of the string. For example,
" he\nllo ".trim() will return "he\nllo" because \n is inside the string.
"h ello".trim() will return "h ello" because the space is inside the string.
Replacing Part of a String
The replace() method takes an old character and a new character as arguments. It returns a new String object by
replacing all occurrences of the old character by the new character. For example,
String oldStr = new String("tooth");
// o in oldStr will be replaced by e. newStr will contain "teeth"
String newStr = oldStr.replace('o', 'e');
Matching Start and End of a String
The startsWith() checks if the string starts with the specified argument, whereas endsWith() checks if the string
ends with the specified string argument. Both methods return a boolean value.
String str = "This is a Java program";
// Test str, if it starts with "This"
if (str.startsWith("This")){
System.out.println("String starts with This");
}
else {
System.out.println("String does not start with This");
}
// Test str, if it ends with "program"
if (str.endsWith("program")) {
System.out.println("String ends with program");
}
else {
System.out.println("String does not end with program");
}
String starts with This
String ends with program
 
Search WWH ::




Custom Search