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

标签 java replace indexof

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

相关文章:

java - 匿名类中的 "Variable example might not have been initialized"

python - 在 Python 中用 NaN 替换一列中的多个字符

php - 替换单词的问题

javascript - 理解 Javascript 中的嵌套数组

java - 如何在创建 jar 文件时包含库文件

用于特定电话号码格式的 Java 正则表达式

java - 哈希集大小操作

sql-server - SQL服务器: how to mass replace fields with result of a query

javascript - Hangman 游戏仅匹配第一个角色,而不是全部

javascript - 尽管对象在数组中,indexOf 仍返回 -1 - Google 电子表格脚本中的 Javascript