Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

string swapping  RSS feed

 
gayathriy Nandakumar
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how do i swap each element in a string with the element of a randomly generated index???
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will have to copy the contents of the String to a mutable object like StringBuffer or into an array, and then after you have finished the swap, convert it back to a String.
 
Campbell Ritchie
Marshal
Posts: 55681
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't swap elements in a String; once created a String cannot be changed. You can however get a new String.
You would be better using a StringBuilder; you can then replace bits with other bits.

BTW: If you replace character a with character b, you will have to record somewhere what a was before you replace b with it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!