Java 实例 - 字符串替换


如何使用java替换字符串中的字符呢?

以下实例中我们使用 java String 类的 replace 方法来替换字符串中的字符:

  1. public class StringReplaceEmp{
  2. public static void main(String args[]){
  3. String str="Hello World";
  4. System.out.println( str.replace( 'H','W' ) );
  5. System.out.println( str.replaceFirst("He", "Wa") );
  6. System.out.println( str.replaceAll("He", "Ha") );
  7. }
  8. }

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

  1. Wello World
  2. Wallo World
  3. Hallo World