Solution of nc1c2

A simple string operations problem. Replace c1 with c2 in the string n, then cast n to an integer and print it.

Basic C solution (Marius Gavrilescu)

    1 #include<stdio.h>
    2 #include<stdlib.h>
    3 #include<string.h>
    4 
    5 int main(void){
    6     while(1){
    7         char c1, c2, n[100], *ch;
    8         scanf("%s %c %c ", n, &c1, &c2);
    9         if(n[0] == '0' && n[1] == 0 && c1 == '0' && c2 == '0')
   10             break;
   11         for (int i = 0 ; i < strlen(n) ; i++)
   12             if(n[i] == c1)
   13                 n[i] = c2;
   14         printf("%d\n", atoi(n));
   15     }
   16     return 0;
   17 }

Slightly shorter C solution (Marius Gavrilescu)

We can use the strchr function to simplify the for loop.
    1 #include<stdio.h>
    2 #include<stdlib.h>
    3 #include<string.h>
    4 
    5 int main(void){
    6     while(1){
    7         char c1, c2, n[100], *ch;
    8         scanf("%s %c %c ", n, &c1, &c2);
    9         if(n[0] == '0' && n[1] == 0 && c1 == '0' && c2 == '0')
   10             break;
   11         while((ch = strchr(n, c1)))
   12             *ch = c2;
   13         printf("%d\n", atoi(n));
   14     }
   15     return 0;
   16 }

Perl solution (Marius Gavrilescu)

We can further improve the solution by switching to another programming language.
    1 #!/usr/bin/perl
    2 use v5.14;
    3 use warnings;
    4 
    5 while (<>) {
    6     my ($n, $c1, $c2) = split ' ';
    7     exit if $n == 0 && $c1 == 0 && $c2 == 0;
    8     $n =~ s/$c1/$c2/g;
    9     say int $n;
   10 }
Questions?

Sponsors Gold