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 " ) ) ;

以上代码实例输出结果为:

Wello World Wallo World Hallo World

Java 实例 Java 实例

public class StringReplaceEmp{ public static void main(String args[]){ String str="Hello World"; String regEx= "[abcdH]"; String reStr= ""; Pattern pattern = Pattern.compile(regEx); Matcher matcher = pattern.matcher(str); // 替换 a、b、c、d、H 为空,即删除这几个字母 reStr = matcher.replaceAll("").trim(); System.out.println( reStr ); }
小猪