Java String replace()

replace() 方法通过用 newChar 字符替换字符串中出现的所有 oldChar 字符,并返回替换后的新字符串。

1 语法

public String replace(char oldChar, char newChar)  

或 

public String replace(CharSequence target, CharSequence replacement)  

2 参数

oldChar :原字符。
newChar : 新字符。
target : 目标字符串
replacement : 替换后的字符串

3 返回值

替换后生成的新字符串。

4 replace()内部源码

public String replace(char oldChar, char newChar) {  
       if (oldChar != newChar) {  
           int len = value.length;  
           int i = -1;  
           char[] val = value; /* avoid getfield opcode */  
  
           while (++i < len) {  
               if (val[i] == oldChar) {  
                   break;  
               }  
           }  
           if (i < len) {  
               char buf[] = new char[len];  
               for (int j = 0; j < i; j++) {  
                   buf[j] = val[j];  
               }  
               while (i < len) {  
                   char c = val[i];  
                   buf[i] = (c == oldChar) ? newChar : c;  
                   i++;  
               }  
               return new String(buf, true);  
           }  
       }  
       return this;  
   }  

5 replace(char old, char new)示例

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java String.replace方法的例子
 */
public class Demo{

    public static void main(String args[]){
        String s1="yiidian is a very good website";
        String replaceString=s1.replace('a','e');//替换所有'a'为'e'
        System.out.println(replaceString);
    }
}

输出结果为:

yiidien is e very good website

6 replace(CharSequence target,CharSequence replacement)示例

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java String.replace方法的例子
 */
public class Demo{

    public static void main(String args[]){
        String s1="my name is eric my name is java";
        String replaceString=s1.replace("is","was");//替换所有"is"为"was"
        System.out.println(replaceString);
    }
}

输出结果为:

my name was eric my name was java

7 replace()示例

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java String.replace方法的例子
 */
public class Demo {

    public static void main(String[] args) {
        String str = "oooooo-hhhh-oooooo";
        String rs = str.replace("h","s"); // 替换'h'为's'
        System.out.println(rs);
        rs = rs.replace("s","h"); // 替换's'为'h'
        System.out.println(rs);
    }
}

输出结果为;

oooooo-ssss-oooooo
oooooo-hhhh-oooooo

 

热门文章

优秀文章