[英]How can I replace the char '2' in a string with the string "to" in Java?
我不确定我使用的是哪个版本的 Java,我使用的是 CodeHS IDE。 我正在尝试在给定的字符串中编写一个“修复语法”的函数。 所有方法需要做的就是用 to 替换所有的 2。 这是我的代码:
public String useProperGrammar(String text) {
String fixedString = new String();
for (int i = 0; i < text.length(); i++) {
fixedString += text.charAt(i);
if (text.charAt(i) == '2') {
fixedString = text.substring(0, i) + text.substring(i + 1);
fixedString += "to";
}
} return fixedString; }
使用String.replace()
方法。
String str = "this is 2";
str = str.replace('2'+"", "to");
System.out.println(str);
如果在字符后附加一个空字符串""
,它会将其转换为字符串并允许替换工作。
如果是字符,则将字符转换为字符串并使用替换方法。
char ch = '2';
String str = Character.toString(ch);
str = str.replace('2' + "", "to");
System.out.println(str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.