Strings Part5
Strings Part5
Strings Part5
Lesson 5
• Lesson Objectives
• To understand the usage of the following String methods
• concat()
• trim()
• replace()
• valueOf()
• lastIndexOf()
Concatenation
concat() – Joins or concatenates two Strings.
string1.concat(string2)
string2 is added to the end of string1
System.out.println("to".concat("get".concat("her")));
Displays, "together“
Difference between concat() and + operator
When numeric data is concatenated with a String, the
+ operator automatically converts the number to a
String, whereas the concat() method does not convert
a number to a String type and the compiler gives an
error.
trim()
This method removes leading and trailing spaces in a
String.
Example:
String s=“ good “;
String s1=“day”;
System.out.println(s+s1);
Output:
good day
System.out.println(s.trim()+s1);
Output:
goodday
replace()
Replaces all occurrences of a character or a String with
another character or String respectively and it returns a new
String. It is case-sensitive.
replace(oldChar, newChar)
The other form:
replace(oldstring, newstring)
String s="mesquite in your cellar“;
String s1=s.replace('e', 'o')
String s1 now contains "mosquito in your collar"
String S2=“teh sun rises in teh east”
System.out.println(S2.replace(“teh”, “the”));
Displays, “the sun rises in the east”, but String S2 remains
unaffected.
More examples for replace()
class stringprog {
public static void main() {
String st="World matters";
System.out.println("before replacing"+st);
st=st.replace("t","$$");
System.out.println("after replacing"+st);
String st1="I am Studying in GMA. GMA is in Dubai";
String s=“12/06/2009”
System.out.println(s.lastIndexOf(‘/’ )); //displays 5