Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

i want to remove spaces from a string to check if its palendrome but it keeps adding letters in C

the issue i have is that the code keeps adding letters after the 'for' code, if i write "ni pratar bra latin" it will become "nipratarbralatintin" with an exta "tin"

    int ret1;
    int size = 0;
    int i = 0;
    char ch[100];


    printf("WELCOME USER
");
    printf("ENTER A SENTENCE OR A WORD FOR THE PROGRAM TO START.
");
    printf("THE PROGRAM WILL CHECK IF YOUR SENTENCE / WORD IS A PALENDROME");
    printf("
");
    scanf(" %[^
]s", &ch);

Removes spaces aka the part im having issues with

    for (i = 0, size = 0; i < strlen(ch); i++) {
        ch[i - size] = ch[i];
        if (ch[i] == ' ')
            size++;
    }
    ch[i] = '';

    ret1 = isPalindrome(ch);
    int quit;

    if (ret1 == 1)
        // 1 means string is palendrome
        printf("
YOUR SENTENCE/WORD: %s IS A PALENDROME", ch);
    else if (ret1 == 0)
        // 0 means string is not palendrome
        printf("
YOUR SENTENCE/WORD: %s IS NOT A PALENDROME", ch);
question from:https://stackoverflow.com/questions/65920652/i-want-to-remove-spaces-from-a-string-to-check-if-its-palendrome-but-it-keeps-ad

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The line

    ch[i] = '';

is wrong. The line is meaningless because will already be there on ch[i] because it is after exiting the loop with the condition i < strlen(ch).

The line should be

   ch[i - size] = '';

to maintain consistency with the line inside the loop ch[i - size] = ch[i];.

Also the line

    scanf(" %[^
]s", &ch);

is wrong because char(*)[100] is passed where char* is expected and undefined behavior is invoked.

It should be

    scanf(" %[^
]s", ch);

without the extra &.

This version with checking is better:

   if (scanf(" %[^
]s", &ch) != 1) {
       fputs("read error
", stderr);
       /* exit program (return from main(), using exit(), etc. */
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...