// 示例代码:使用 replace 方法替换字符串中的字符或子字符串
public class ReplaceExample {
public static void main(String[] args) {
// 定义一个原始字符串
String originalString = "Hello, World!";
// 使用 replace 方法将 'o' 替换为 'a'
String replacedString = originalString.replace('o', 'a');
System.out.println("Replace 'o' with 'a': " + replacedString);
// 使用 replace 方法将子字符串 "World" 替换为 "Java"
String replacedSubstring = originalString.replace("World", "Java");
System.out.println("Replace 'World' with 'Java': " + replacedSubstring);
}
}
replace(char oldChar, char newChar): 该方法用于将字符串中所有出现的指定字符 oldChar
替换为新的字符 newChar
。在示例中,我们将所有的 'o' 替换为 'a'。
replace(CharSequence target, CharSequence replacement): 该方法用于将字符串中所有出现的指定子字符串 target
替换为新的子字符串 replacement
。在示例中,我们将子字符串 "World" 替换为 "Java"。
这两个方法都返回一个新的字符串,原字符串不会被修改。
上一篇:java threadlocal
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站