java String类中 有个replace()方法, 假设 String s="1231" 我现在只想把第一个位置的'1'替换为 '2' 怎么弄 ? 如果 s=s.replace(s.charAt(0),'2') 那么第4个位置的1也会变为'2' 结果就成了s="2232"
#include<algorithm>
#include<string>
#include<iostream>
(此处空一行)
using namespace std;
int main()
{
string str="123/421657/abcd///456789";
(此处空一行)
cout << str << endl;
replace(str.begin(),str.end(),'/',' ');
cout << str << endl;
return 0;
}
注:使用StringBuilder来构建字符串,然后可以使用strBuilder.setCharAt(1, '');来修改某一字符,如果要将字符串的所有特定字符全部替换,string中可以使用replaceAll("","");方法。
String字符串操作
replace(oldChar, newChar)方法 参数1:要被替换的字符,参数2:替换进去的字符
该方法的作用是替换字符串中所有指定的字符,然后生成一个新的字符串。经过该方法调用以后,原来的字符串不发生改变。例如:
String s = "abcde8fghijk8lmn";
String a = s.replace('8', 'Q');
a的值为"abcdeQfghijkQlmn"
java String可以用 StringBuilder 这个类试试,里面有一个接口replace,如下代码:
运行结果如下:
好方法 3Q