java Sting 如何替换指定位置的 字符?

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"

温馨提示:内容为网友见解,仅供参考
第1个回答  2015-11-12

java String可以用 StringBuilder 这个类试试,里面有一个接口replace,如下代码:

package com.qiu.lin.he;

import java.text.ParseException;

public class Ceshi {
public static void main(String[] args) throws ParseException {

// 可以用 StringBuilder 这个类,里面有一个接口replace,如下
StringBuilder sb = new StringBuilder("abcd");
sb.replace(1, 2, "测试是否替换指定的第二个元素");
System.out.println(sb.toString());

}
}

运行结果如下:

第2个回答  2012-04-22
换个思路,用StringBuffer,所谓替换就是删除指定位置的值,然后再向指定位置插入你要的值
int index = 1; //你指定的位置
StringBuffer sb = new StringBuffer (s);
sb.deleteCharAt(index-1);//减1是因为java中String的索引是从0开始的,如果我们所指定的index以0开始的话,这里可以不用减1
sb.insert(index-1,"2");
System.out.println(sb.toString());追问

好方法 3Q

第3个回答  2019-01-16
试试这个,带测试
public class test {
String word="111111";
String hex="33";

/**
* 替换String oldWord中第start到end位的字符为String word
* @return
* */
public static String replaceWord(String oldWord,int start,int end,String word) {
StringBuilder newWord =new StringBuilder(oldWord);
newWord.replace(start, end,word);
return newWord.toString();
}
String newWord=replaceWord(word,2,4,hex);
public static void main(String[] args){
test a=new test();
System.out.println(a.word);
System.out.println(a.newWord);

}
}
第4个回答  2012-04-22
s = s.replace("1","2");就是这样,只会替换第一个
相似回答