Character replacement#8987

Character replacement (Editorial)

Read the input string and replace all occurrences of '' with '' 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 '' is replaced with ''. Each letter '' is replaced with ''.

for (int 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 '' is replaced with ''. Each letter '' is replaced with ''.

for (int 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 '' with the character '', 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 '' with the letter ''.

s = s.replace('b','a')

Replace all occurrences of the letter '' with the letter ''.

s = s.replace('0','b')

Print the updated string.

print(s)