Reputation: 61
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
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
Reputation: 40145
String newWord = word.replace("e","_e_").replace("h","e").replace("_e_","h");
Upvotes: 0
Reputation: 6174
Strings in java are immutable. Hence, technically, in String b you can not swap spaces of characters.
The only workaround is to
char[]
char[]
char[]
Upvotes: 2