Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

java - 替换字符串中特定索引处的字符?(Replace a character at a specific index in a string?)

I'm trying to replace a character at a specific index in a string.

(我正在尝试替换字符串中特定索引处的字符。)

What I'm doing is:

(我正在做的是:)

String myName = "domanokz";
myName.charAt(4) = 'x';

This gives an error.

(这给出了一个错误。)

Is there any method to do this?

(有什么方法可以做到这一点?)

  ask by dpp translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

String are immutable in Java.

(字符串在Java中是不可变的。)

You can't change them.

(您不能更改它们。)

You need to create a new string with the character replaced.

(您需要创建一个新字符串并替换字符。)

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can use a StringBuilder:

(或者,您可以使用StringBuilder:)

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...