java - 如何在奇数索引处用“*”替换字符,否则用“+”替换
问题描述
如果 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[]
您可能会发现使用 a比使用 a更容易String
,因为 aString
是不可变的,这意味着您必须不断创建新String
对象。首先转换为 a 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);
}
推荐阅读
- python - 如何在 mongoengine/pymongo 中设置固定字段
- javascript - 当用户向上或向下滚动时触发滚动事件 react.js
- javascript - 仅在视口中进行动画处理
- laravel - 我在使用 laravel scout 时遇到此错误:您的要求无法解决为一组可安装的软件包
- c++ - 通过套接字 C++ 发送 XML 文件
- swift - 快速参数标签和关键字
- python - ACS ACR122U 使用 Python NFC 工具库在屏幕上显示标签
- css - 减少 CSS 中的文本视图容器大小
- python - Daphne 在使用 Django ASGI 的浏览器上显示空白屏幕,无法加载静态文件。为什么?
- c# - Convert.ToDateTime('Datestring') 到所需的 dd-MMM-yyyy 日期格式