replace() method
'replace' method takes pair of characters or pair of CharSequences and return a string by replacing every occurrence of char or CharSequence with newChar or newCharSequence
Signature
public String replace(CharSequence target, CharSequence newCharSequence)
public String replace(char oldChar, char newChar)
package com.sample.app;
public class App {
public static void main(String args[]) {
String str1 = "You're braver than you believe, and stronger than you seem, and smarter than you think.";
String str2 = str1.replace("and", "->");
String str3 = str1.replace('b', 'B');
System.out.println("str1 : " + str1);
System.out.println("str2 : " + str2);
System.out.println("str3 : " + str3);
}
}
Output
str1 : You're braver than you believe, and stronger than you seem, and smarter than you think. str2 : You're braver than you believe, -> stronger than you seem, -> smarter than you think. str3 : You're Braver than you Believe, and stronger than you seem, and smarter than you think.
replaceAll method
'replaceAll' method takes a regular expression and replacement string as arguments and return a string by replacing each substring of this string that matches the given regular expression.
Signature
public String replaceAll(String regex, String replacement)
package com.sample.app;
public class App {
public static void main(String args[]) {
String str1 = "You're braver than you believe, and stronger than you seem, and smarter than you think.";
String str2 = str1.replaceAll(".o.", "###");
System.out.println("str1 : " + str1);
System.out.println("str2 : " + str2);
}
}
Output
str1 : You're braver than you believe, and stronger than you seem, and smarter than you think. str2 : ###'re braver than ### believe, and st###ger than ### seem, and smarter than ### think.
You may
like
No comments:
Post a Comment