Java: replace a set of characters with other different characters

后端 未结 4 1544
梦谈多话
梦谈多话 2021-01-23 09:22

I am supposed to make a custom decorator so I can replace both in an input from console and from a file:

  1. A set of chars with a specific character (e.g. char[
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-23 10:02

    There is a more faster way:

    public static void main(String[] args) {
        String target      = "ab";
        String replacement = "**";
    
        char[] array = "abcde".toCharArray();
        for (int i = 0; i < array.length; i++) {
            int index = target.indexOf(array[i]);
            if (index != -1) {
                array[i] = replacement.charAt(index);
            }
        }
    
        System.out.println(array);
    }
    

提交回复
热议问题