morgothraud
morgothraud

Reputation: 61

How to change the position of characters in a String?

For example,

String a = "horse" ; String b = "eshor" ;

How can I change the locations of E and H in string B ?

Note : I cannot use String builder. I want to change them by their position. I need to reveal the first character.

output should be something like :

shuffled word : eshor

new word :hseor

Upvotes: 0

Views: 2845

Answers (3)

Ozan Aksoy
Ozan Aksoy

Reputation: 306

Your question is vague, so I cannot get what your purpose actually is.

You cannot change a String object, because they are immutable. If what you mean with "I cannot use a string builder" is that you cannot use the String object or string casters. then you can operate on chars directly, like this:

    char[] cycleChars(String str, int fIndex, int sIndex){
    char[] cArr = str.toCharArray();
    char cTemp;
        cTemp = cArr[fIndex];
        cArr[fIndex] = cArr[sIndex];
        cArr[sIndex] = cTemp;
        return cArr;
}

Maybe all you need is a simple op method such as the one above.

Upvotes: 0

BLUEPIXY
BLUEPIXY

Reputation: 40145

String newWord = word.replace("e","_e_").replace("h","e").replace("_e_","h");

Upvotes: 0

Amit Sharma
Amit Sharma

Reputation: 6174

Strings in java are immutable. Hence, technically, in String b you can not swap spaces of characters.

The only workaround is to

  1. Convert String to char[]
  2. Flip chars in char[]
  3. Create a new String with reordered char[]

Upvotes: 2

Related Questions