String replace
In this chapter you will learn:
- Replaces all occourances of given character with new one and returns new String object
- Replaces only first occourances of given String with new one and returns new String object
- Replaces all occourances of given String with new one and returns new String object
- How to replace escaped string
- Replace \r\n with the <br> tag
Replaces all occourances
The following code shows how to use replace()
to
replaces all occourances of given character with new one and returns new String object.
public class Main {
/*j a v a2s . co m*/
public static void main(String args[]) {
String str = "This is a test from java2s.com.";
System.out.println(str.replace('T', 'A'));
}
}
The code above generates the following result.
Replaces only first occourances
public class Main {
//from j a v a 2 s. co m
public static void main(String args[]) {
String str = "This is a test. This is a test from java2s.com";
System.out.println(str.replaceFirst("Th", "Ab"));
}
}
The code above generates the following result.
Replace All
public class Main {
/*from j a v a 2s. c o m*/
public static void main(String args[]) {
String str = "This is a test.";
System.out.println(str.replaceAll("is", "are"));
}
}
The code above generates the following result.
Replace and escape
public class Main {
public static void main(String args[]) {
String myString = "'''";
String tmpString = myString.replace('\'', '*');
System.out.println("Original = " + myString);
System.out.println("Result = " + tmpString);
}//from ja v a 2 s .co m
}
The code above generates the following result.
Replace \r\n with the <br> tag
public class Main {
public static void main(String[] argv) {
//from j a v a 2s .c o m
System.out.println("\r\n|\r|\n|\n\r".replaceAll("(\r\n|\r|\n|\n\r)", "<br>"));
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » String