Search code examples
cstringswitch-statementswapletters

Switching letters in a string in C


I'm not sure why this code does not work.

This code is supposed to, for example, switch all a's in the string to b's, and all b's to a's and print the result.

input:

abcd
a b
c d

Intended output:

badc

Code:

int main()
{
    int n, m, i, j;

    scanf("%d %d", &n, &m);

    char s[n+1], x[m+1], y[m+1];

    scanf("%s", s);

    for(i=0; i<m; i++)
    {
        scanf("%c", &x[i]);
        scanf("%c", &y[i]);
    }

    for(j = 0; j < m; j++)
    {
        for(i = 0; i<n; i++)
        {
            if(s[i] == x[j])
                s[i] = y[j];
            else if(s[i] == y[j])
                s[i] = x[j];
        }
    }

    printf("%s", s);

    return 0;
}

Solution

  • As I commented you need a space before the %c in these lines

    scanf("%c", &x[i]);
    scanf("%c", &y[i]);
    

    to prevent the %c format type reading the white-space left in the input buffer by previous scanf calls. Change to

    scanf(" %c", &x[i]);
    scanf(" %c", &y[i]);