Replacement of the symbol on another



  • Replace all the symbols of position (3) with the symbol of position 0. Don't tell me how to do it. It's from index 0 to index 3, I only know by replace



  • Try the following code:

            public static void main(String[] args) {
                String exampleStr = "Hello, World!";
                // Замена всех символов с 0 позиции ('H') на символ с 3 позиции ('l')
                System.out.println(replaceAllByIndex(exampleStr, 0, 3));
                // Замена всех символов с 4 позиции ('o') на символ с 12 позиции ('!')
                System.out.println(replaceAllByIndex(exampleStr, 4, 12));
            }
    
        public static String replaceAllByIndex(String input, int dstIdx, int srcIdx) {
            return input.replace(input.charAt(dstIdx), input.charAt(srcIdx));
        }
    

    It's a function. replaceAllByIndex performs the replacement of all symbols on the index dstIdx with index symbol srcIdx in line input

    However, if your purpose is simply to change the places of two symbols (not all driving), use the following function instead. replaceAllByIndex in code above:

            public static String swapChars(String input, int lIdx, int rIdx) {
    StringBuilder sb = new StringBuilder(input);
    sb.setCharAt(lIdx, input.charAt(rIdx));
    sb.setCharAt(rIdx, input.charAt(lIdx));
    return sb.toString();
    }

    Programme findings in the first and second cases, respectively:

    введите сюда описание изображения введите сюда описание изображения



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2