String Replace
# Java Example - String Replacement
[ Java Example](#)
How to use Java to replace characters in a string?
In the following example, we use the `replace` method of the Java `String` class to replace characters in a string:
## StringReplaceEmp.java File
```java
public class StringReplaceEmp{
public static void main(String args[]){
String str="Hello World";
System.out.println(str.replace('H','W'));
System.out.println(str.replaceFirst("He", "Wa"));
System.out.println(str.replaceAll("He", "Ha"));
}
}
The output of the above code example is:
Wello World
Wallo World
Hallo World
[ Java Example](#)
## 1 Note
1. #0 Little Pig
123***1070@qq.com [](#)48 Using regular expressions to replace specified characters in a string:
```java
import java.util.regex.*;
public class StringReplaceEmp{
public static void main(String args[]){
String str="Hello World";
String regEx= "";
String reStr= "";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(str);
// Replace a, b, c, d, H with empty string, i.e., delete these letters
reStr = matcher.replaceAll("").trim();
System.out.println( reStr );
}
}
```
(javascript:;)Little Pig
123***1070@qq.com 8 years ago (2018-05-29)
YouTip