Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two letters in a string

Tags:

java

string

regex

I want to swap two letters in a string. For example, if input is W and H then all the occurrences of W in string should be replaced by H and all the occurrences of H should be replaced by W. String WelloHorld will become HelloWorld.

I know how to replace single char:

str = str.replace('W', 'H');

But I am not able to figure out how to swap characters.

like image 637
Jainendra Avatar asked Oct 11 '14 16:10

Jainendra


People also ask

How do you swap characters in a string?

Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time.

How to swap two strings in Python?

First of all, the program has 2 strings attached to the user and will store them in a variable. After this, we will swap the first two variables of the given strings using the Python slicking method and replus () method. Also keep them in new variables. In the last, we will print those new variables. In which we put the swap strings.

How do you find the final string after B swaps?

Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your task is to find the final String after B swaps.

How do you divide a string into two parts?

We can find that the string is divided into two parts: the first part of length C comprising of the first C characters of S, and the second part comprising of the rest of the characters. The two parts are rotated by some places. The first part is rotated right by (N % C) places every full iteration.


1 Answers

public String getSwappedString(String s)
{
char ac[] = s.toCharArray();
for(int i = 0; i < s.length(); i++)
{
   if(ac[i] == 'H')
     ac[i]='W';
   else if(ac[i] == 'W')
     ac[i] = 'H'; 
}

s = new String(ac);
return s;
}
like image 101
Arjuna Avatar answered Oct 03 '22 12:10

Arjuna