如果 s char 位于奇数索引处,我想用“+”替换它,否则用“*”
这是我的代码
//calling emphasize(shanuss,s)
//expected output +hanu*+
public static String emphasize(String phrase ,char ch) {
String l = phrase;
char c = ch;
int s = l.indexOf(c);
while (s >= 0) {
if(s%2==0)
{ l=l.replace(l.charAt(s),'+');}
else{l=l.replace(l.charAt(s),'*');}
s = l.indexOf(c, s + 1);
}
return l;
}
谢谢
最佳答案
您可能会发现使用 char[]
比使用 String
更容易,因为 String
是不可变的,这意味着您必须不断创建新的 String 对象。首先转换为 char[]
,然后迭代它。
public static String emphasize(String phrase, char toReplace) {
char[] characters = phrase.toCharArray();
for (int index = 0; index < characters.length; index++ ) {
if (characters[index] == toReplace) {
characters[index] = index % 2 == 1 ? '+' : '*';
}
}
return new String(characters);
}
关于java - 如何在奇数索引处用 '*' 替换字符,否则用 '+',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50790740/