java string replace() 方法返回一個字符串,將所有舊的 char 或 CharSequence 替換為新的 char 或 CharSequence。
從 JDK 1.5 開始,引入了一個新的 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;
}
簽名
java字符串中有兩種替換方法。
public String replace(char oldChar, char newChar)
and
public String replace(CharSequence target, CharSequence replacement)
從 JDK 1.5 開始添加了第二個替換方法。
參數
oldChar:老字號
newChar:新角色
target:目標字符序列
replacement:替換字符序列
返回
替換字符串
Java String replace(char old, char new) 方法示例
public class ReplaceExample1{
public static void main(String args[]){
String s1="javatpoint is a very good website";
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
System.out.println(replaceString);
}}
jevetpoint is e very good website
Java String replace(CharSequence target, CharSequence replacement) 方法示例
public class ReplaceExample2{
public static void main(String args[]){
String s1="my name is khan my name is java";
String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"
System.out.println(replaceString);
}}
my name was khan my name was java
Java 字符串 replace() 方法示例 3
public class ReplaceExample3 {
public static void main(String[] args) {
String str = "oooooo-hhhh-oooooo";
String rs = str.replace("h","s"); // Replace 'h' with 's'
System.out.println(rs);
rs = rs.replace("s","h"); // Replace 's' with 'h'
System.out.println(rs);
}
}
oooooo-ssss-oooooo oooooo-hhhh-oooooo
相關用法
- Java String replaceAll()用法及代碼示例
- Java String repeat()用法及代碼示例
- Java String valueOf()用法及代碼示例
- Java String getChars()用法及代碼示例
- Java String substring()用法及代碼示例
- Java String contains()用法及代碼示例
- Java String copyValueOf()用法及代碼示例
- Java String isEmpty()用法及代碼示例
- Java String toString()用法及代碼示例
- Java String endsWith()用法及代碼示例
- Java String split()用法及代碼示例
- Java String lines()用法及代碼示例
- Java String strip()用法及代碼示例
- Java String lastIndexOf()用法及代碼示例
- Java String equals()用法及代碼示例
- Java String subSequence()用法及代碼示例
- Java String startsWith()用法及代碼示例
- Java String getBytes()用法及代碼示例
- Java String indexOf()用法及代碼示例
- Java String charAt()用法及代碼示例
注:本文由純淨天空篩選整理自 Java String replace()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。