Contents

Changing index (with.Java)

   Feb 26, 2024     1 min read

This article looks into the “changing index” problem.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

When the string my_string and the integers num1 and num2 are given as parameters, complete the solution function to return a string with the characters corresponding to index num1 and index num2 in my_string changed.

Restrictions

  • 1 < length of my_string < 100
  • 0 ≤ num1, num2 < length of my_string
  • my_string consists of lowercase letters.
  • num1 ≠ num2

Input/Output Example

my_stringnum1num2result
“hello”12“hlelo”
“I love you”36“I l veoyou”

My solution to the problem

class Solution {
     public String solution(String my_string, int num1, int num2) {
         char[] ch = my_string.toCharArray();

         ch[num1] = my_string.charAt(num2);
         ch[num2] = my_string.charAt(num1);

         String answer = String.valueOf(ch);
         return answer;
     }
}

Solution explanation

  • First, convert the given string to a char array. And replace the character at position ch[num1] with my_string.charAt(num2), and replace the character at position ch[num2] with my_string.charAt(num1).
  • After completing the character exchange, convert the char array back to a string and store it in the answer variable. Finally, it returns an answer.
  • In other words, the solution method performs a function that returns the result of exchanging the characters at positions num1 and num2 in the given string.