首页 > 解决方案 > 如何在奇数索引处用“*”替换字符,否则用“+”替换

问题描述

如果 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;
    }

谢谢

标签: javareplaceindexof

解决方案


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);
}

推荐阅读