Home > front end >  I want to swap characters of string in java but it returns garbage value can you please tell me what
I want to swap characters of string in java but it returns garbage value can you please tell me what

Time:03-19

I want to swap characters of string but this program returns garbage value. Can you please tell me what is wrong with my code.

public static String swap(String str,int x,int y) {
    char arr[]=str.toCharArray();
    char temp=arr[x];
    arr[x]=arr[y];
    arr[y]=temp;
    String str2=arr.toString();
    return str2;
}

CodePudding user response:

You have to use constructor of String class. Then it will work fine.

public static String swap(String str,int x,int y) {
    char arr[]=str.toCharArray();
    char temp=arr[x];
    arr[x]=arr[y];
    arr[y]=temp;
    return new String(arr);
}
  • Related