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.
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With