简体   繁体   中英

How to recognize space after first word in string?

I have created a very simple program that is supposed to match a string where the first word ("abc") ends with a white space. If I write, for example, "abc defg" I should receive a match because of "abc" and the white space. If I write "abcdefg" I should not because there are no white space.

I guess my first solution didn't really work out because a white space simply isn't a character (?). I therefore created the second solution below with a second condition in the IF-statement, however, it didn't work out neither...

Any ideas how a space in the end of a string can be recognized ?

int main(void) 
{
    while(1)
    {
        char str[30];

        scanf("%s", str);

        char *word = "abc ";      <------------ QUESTION HERE

        // If two first three letters are "abc" + white space
        if(strncmp(str, word, 4) == 0) {

            printf("Match\n");

        } else {

            printf("No match\n");

        }
    }

}

Second code:

int main(void) 
{
    while(1)
    {
        char str[30];

        scanf("%s", str);

        char *word = "abc";

        // If two first three letters are "abc" + white space
        if(strncmp(str, word, 3) && (isspace(str[3])) == 0) {

            printf("Match\n");

        } else {

            printf("No match\n");

        }
    }

}

I guess my first solution didn't really work out because a white space simply isn't a character (?)

Of course whitespace is a character - in fact, a group of characters are considered whitespace. However, whitespace characters play special role when it comes to scanf : it serves to separate inputs parsed with the format string, except a few special cases.

That is why you are not going to get "abc " from scanf with %s : the trailing whitespace would always be ignored, so neither of your two approaches would work.

This would work:

char buf[100], ch;
scanf("%99s%c", buf, &ch);
if (strcmp(buf, "abc") == 0 && ch == ' ') {
    printf("Yes!\n");
}

The idea is to read the character immediately after %s 's capture into a variable, and compare that variable to space character ' ' .

Note the use of %99s to limit the size of the input to the allocated length of the buffer (plus an additional character for the null terminator).

Demo.

Important: It goes without saying that you need to check the return value of scanf to see that there was some input for all format specifiers. In the case above you need to check that scanf 's return value was 2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM