5

你如何得到一个字符串的最后一个单词,从 '\0' 换行符开始到最右边的空格?例如,我可以有这样的东西,其中 str 可以被分配一个字符串:

char str[80];
str = "my cat is yellow";

我怎么会变黄?

4

5 回答 5

11

像这样的东西:

char *p = strrchr(str, ' ');
if (p && *(p + 1))
    printf("%s\n", p + 1);
于 2012-02-09T22:36:03.827 回答
1

如果您不想使用“strrchr”功能,这里是解决方案。

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++;
}
于 2018-10-16T03:44:41.813 回答
0

我会使用功能strrchr()

于 2012-02-09T22:36:52.313 回答
-2

最好的方法是利用现有的解决方案。一个这样的解决方案(针对更普遍的问题)是Perl Compatible Regular Expressions,这是一个 C 的开源正则表达式库。因此,您可以将字符串“my cat is yellow”与正则表达式 \b(\w+) 匹配$(在 C 中表示为“\b(\w+)$”)并保留第一个捕获的组,即“黄色”。

于 2012-02-09T22:38:04.017 回答
-2

(沉重的叹息)标准/K&R/ANSI C 中的原始代码是错误的!它不会初始化字符串(名为 str 的字符数组)!如果示例编译,我会感到惊讶。您的程序段真正需要的是

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

或者,如果您承诺不尝试操作字符串,您可以在源代码中使用指向硬编码的“my cat is yellow”字符串的 char 指针。

如果,如前所述,“单词”以空格字符或 NULL 字符为界,那么声明一个字符指针并从 NULL 之前的字符向后走会更快。显然,您首先必须确保有一个非空字符串....

#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);
    }

现在您可以争辩说任何非字母字符都应该标记单词边界,例如“Dogs-chase-cats”或“my cat:yellow”。在那种情况下,很容易说

if (!isalpha(*cPtr) )

在循环中,而不是仅仅寻找一个空间......

于 2012-02-10T06:15:19.037 回答