Replace all occurrences of the letter ‘a’ with ‘b’ and
vice versa in the given string.
Input. One string with a length of no more than 200
characters, containing only Latin letters and spaces.
Output. Print the string with the replacements made.
Sample input |
Sample output |
abrakadabra |
barbkbdbarb |
strings
Algorithm
analysis
Read the input string and replace all occurrences of ‘a’ with ‘b’
and vice versa.
Algorithm implementation
Declare a character array to store the string.
char s[200];
Read the input string.
gets(s);
Iterate
over the characters of the string. Each letter ‘a’ is
replaced with ‘b’. Each letter ‘b’ is replaced with ‘a’.
for (i = 0; i < strlen(s);
i++)
if (s[i] == 'a') s[i] = 'b';
else if (s[i] == 'b') s[i] = 'a';
Print the
updated string.
puts(s);
Algorithm implementation – Ñ++
Read the input string.
getline(cin,
s);
Iterate
over the characters of the string. Each letter ‘a’ is
replaced with ‘b’. Each letter ‘b’ is replaced with ‘a’.
for (i = 0; i < s.size();
i++)
if (s[i] == 'a') s[i] = 'b';
else if (s[i] == 'b') s[i] = 'a';
Print the
updated string.
cout << s << endl;
Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new
Scanner(System.in);
String s = con.nextLine();
s = s.replace('a', '0');
s = s.replace('b', 'a');
s = s.replace('0', 'b');
System.out.println(s);
con.close();
}
}
Python implementation
Read the input string.
s = input()
Temporarily replace all occurrences of the letter ‘a’
with the character ‘0’, which does not appear in the string. The replace
method does not modify the original string but returns a new string with the
replacements. This is because strings in Python are immutable.
s = s.replace('a','0')
Replace all occurrences of the letter ‘b’ with
the letter ‘a’.
s = s.replace('b','a')
Replace all occurrences of the letter ‘0’ with the
letter ‘b’.
s = s.replace('0','b')
Print the
updated string.
print(s)