gpt4 book ai didi

java - 如何在奇数索引处用 '*' 替换字符,否则用 '+'

转载 作者:行者123 更新时间:2023-12-01 19:52:39 25 4
gpt4 key购买 nike

如果 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com