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