traversing C string: get the last word of a string

前端 未结 5 1084
终归单人心
终归单人心 2021-01-13 03:26

how would you get the last word of a string, starting from the \'\\0\' newline character to the rightmost space? For example, I could have something like this where str coul

相关标签:
5条回答
  • 2021-01-13 03:32

    In case you don't want to use 'strrchr' function, Here is the solution.

    i = 0;
    char *last_word;
    
    while (str[i] != '\0')
    {
        if (str[i] <= 32 && str[i + 1] > 32)
            last_word = &str[i + 1];
        i++;
    }
    i = 0;
    while (last_word && last_word[i] > 32)
    {
        write(1, &last_word[i], 1);
        i++;
    }
    
    0 讨论(0)
  • 2021-01-13 03:33

    I would use function strrchr()

    0 讨论(0)
  • 2021-01-13 03:38

    Something like this:

    char *p = strrchr(str, ' ');
    if (p && *(p + 1))
        printf("%s\n", p + 1);
    
    0 讨论(0)
  • 2021-01-13 03:38

    The best way to do this is to take advantage of existing solutions. One such solution (to a much more general problem) is Perl Compatible Regular Expressions, an open-source regular expression library for C. So, you can match the string "my cat is yellow" with the regular expression \b(\w+)$ (expressed in C as "\b(\w+)$") and keep the first captured group, which is "yellow."

    0 讨论(0)
  • 2021-01-13 03:40

    (heavy sigh) The original code is WRONG in standard / K&R / ANSI C! It does NOT initialize the string (the character array named str)! I'd be surprised if the example compiled. What your program segment really needs is

    if strcpy(str, "my cat is yellow")
        {
        /* everything went well, or at least one or more characters were copied. */
        }
    

    or, if you promised not to try to manipulate the string, you could use a char pointer to the hard-coded "my cat is yellow" string in your source code.

    If, as stated, a "word" is bounded by a space character or a NULL character, then it would be faster to declare a character pointer and walk backwards from the character just before the NULL. Obviously, you'd first have to be sure that there was a non-empty string....

    #define NO_SPACE 20
    #define ZERO_LENGTH -1
    
    int iLen;
    char *cPtr;
    
    if (iLen=strlen(str) ) /* get the number of characters in the sting */
        { /* there is at least one character in the string */
        cPtr = (char *)(str + iLen); /* point to the NULL ending the string */
        cPtr--; /* back up one character */
        while (cPtr != str)
            { /* make sure there IS a space in the string
                 and that we don't walk too far back! */
            if (' ' == *cPtr)
                { /* found a space */
    /* Notice that we put the constant on the left?
       That's insurance; the compiler would complain if we'd typed = instead of == 
     */
                break;
                }
            cPtr--; /* walk back toward the beginning of the string */
            }
        if (cPtr != str)
            { /* found a space */
            /* display the word and exit with the success code */
            printf("The word is '%s'.\n", cPtr + 1);
            exit (0);
            }
        else
            { /* oops.  no space found in the string */
            /* complain and exit with an error code */
            fprintf(STDERR, "No space found.\n");
            exit (NO_SPACE);
            }
        }
    else
        { /* zero-length string.  complain and exit with an error code. */
        fprintf(STDERR, "Empty string.\n");
        exit (ZERO_LENGTH);
        }
    

    Now you could argue that any non-alphabetic character should mark a word boundary, such as "Dogs-chase-cats" or "my cat:yellow". In that case, it'd be easy to say

    if (!isalpha(*cPtr) )
    

    in the loop instead of looking for just a space....

    0 讨论(0)
提交回复
热议问题