Java中的字符串是字符数组内部支持的对象。由于数组是不可变的,字符串也是一种保存字符的特殊数组,因此字符串也是不可变的。
这个 Java的字符串类 包含许多方法来对字符串执行各种操作,例如compare()、concat()、equals()、split()、length()、replace()、compareTo()、substring()等。在这些方法中,我们将重点介绍 替换() 方法
一串replace()方法
此方法返回 一个新的字符串 将字符串中所有出现的旧字符替换为新字符。这是 3. 变种 替换() 方法本文对所有这些问题进行了如下描述:
1.字符串替换(): 这种方法 返回 将字符串中所有出现的旧字符替换为新字符而生成的新字符串。
语法:
public String replace(char oldch, char newch)
参数:
- 老话: 老角色。
- 纽奇: 新角色。
返回值: 它通过将每次出现的oldch替换为newch,返回从该字符串派生的字符串。
例子:
JAVA
// Java code to demonstrate the // working of replace() public class rep1 { public static void main(String args[]) { // Initialising String String Str = new String( "Welcome to geeksforgeeks" ); // Using replace to replace characters System.out.print( "After replacing all o with T : " ); System.out.println(Str.replace( 'o' , 'T' )); // Using replace to replace characters System.out.print( "After replacing all e with D : " ); System.out.println(Str.replace( 'e' , 'D' )); } } |
After replacing all o with T : WelcTme tT geeksfTrgeeks After replacing all e with D : WDlcomD to gDDksforgDDks
2.字符串replaceAll(): 这种方法取代了 每个子串 将给定的正则表达式与给定的replace_str匹配的字符串。
语法:
public String replaceAll(String regex, String replace_str)
参数:
- 正则表达式: 此字符串要与之匹配的正则表达式。
- 替换_str: 将替换找到的表达式的字符串。
返回值: 此方法返回结果字符串。
例子:
JAVA
// Java code to demonstrate the // working of replaceAll() public class rep2 { public static void main(String args[]) { // Initialising String String Str = new String( "Welcome to geeksforgeeks" ); // original string System.out.print( "Original String : " ); System.out.println(Str); // Using replaceAll to replace regex with // replace_str System.out.print( "After replacing regex with replace_str : " ); System.out.println( Str.replaceAll( "(.*)geeks(.*)" , "ASTHA TYAGI" )); } } |
Original String : Welcome to geeksforgeeks After replacing regex with replace_str : ASTHA TYAGI
3.字符串replaceFirst(): 此方法取代了 第一个子串 将给定正则表达式与给定的replace_str匹配的字符串。
语法:
public String replaceFirst(String regex, String replace_str)
参数:
- 正则表达式: 此字符串要与之匹配的正则表达式。
- 替换_str: 将替换找到的表达式的字符串。
返回值: 此方法返回结果字符串。
例子:
JAVA
// Java code to demonstrate the // working of replaceFirst() public class rep3 { public static void main(String args[]) { // Initialising String String Str = new String( "Welcome to geeksforgeeks" ); // original string System.out.print( "Original String : " ); System.out.println(Str); // Using replaceFirst to replace regex with // replace_str Replaces 1st occurrence of geeks with // ASTHA System.out.print( "After replacing 1st occurrence of regex with replace_str : " ); System.out.println( Str.replaceFirst( "geeks" , "ASTHA" )); } } |
Original String : Welcome to geeksforgeeks After replacing 1st occurrence of regex with replace_str : Welcome to ASTHAforgeeks
本文由 阿斯塔·蒂亚吉 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。