Page 352 - Computer science 868 Class 12
P. 352
12. String replace(String stringtorep, String stringtoadd): This method replaces all the sequence of characters in
stringtorep with the sequence of characters in stringtoadd and creates a new String. It replaces all the sets having
the same sequence.
Syntax: String <variable> = Stringobject.replace(String stringtorep, String stringtoadd);
Example:
String str = "bad Students get bad marks";
String replacestr = str.replace("bad", "good");
System.out.println("The replaced string is :" +replacestr);
Output:
The replaced string is: good students get good marks
13. boolean equals(String str): This method checks whether the string of the current string object whose method is
called is same as the string str in the parameter. It returns true if both the strings are equal, else returns false. This
function is case-sensitive.
Syntax: boolean <variable> = Stringobject.equals(String str);
Example:
String w1 = "Computer";
String w2 = "Computer";
boolean check= w1.equals(w2);
if(check)
System.out.println(w1 + " and " + w2 + "are equal");
else
System.out.println (w1 + " and " + w2 + "are not equal");
Output:
Computer and Computer are equal
14. boolean equalsIgnoreCase(String str): This method is similar to equals() which checks whether the string of the
current string object whose method is called is same as the string str in the parameter. But the difference is that
it is not case-sensitive. It returns true if both the strings are equal even if they are of different cases, else returns
false.
Syntax: boolean <variable> = Stringobject.equalsIgnoreCase(String str);
Example:
String w1 = "CompuTER";
String w2 = "COMputer";
boolean check= w1.equalsIgnoreCase(w2);
if(check)
System.out.println("The strings are equal");
else
System.out.println("The strings are not equal");
Output:
The strings are equal
15. int compareTo(String str): This method compares the given string in the parameter with string in the current
object alphabetically. It returns integer value, i.e., the difference between the ASCII codes of the characters that
are compared. If both the strings are equal, it returns 0. If the first string is larger lexicographically than the second
string, it returns a positive number else returns a negative value.
Comparison is based on the first string.
if str1>str2 : it returns a positive value
if str1<str2 : it returns a negative value
350350 Touchpad Computer Science-XII

