你怎么能得到一个字符串的最后一个字,从'\ 0'换行符到最右边的空格?例如,我可以在这样的地方为str分配一个字符串:
char str[80];
str = "my cat is yellow";
我怎么会变黄?
答案 0 :(得分:9)
这样的事情:
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
答案 1 :(得分:0)
我会使用函数strrchr()
答案 2 :(得分:0)
如果您不想使用'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++;
}
答案 3 :(得分:-2)
最好的方法是利用现有的解决方案。一个这样的解决方案(对于一个更普遍的问题)是Perl Compatible Regular Expressions,一个用于C的开源正则表达式库。因此,您可以将字符串“my cat is yellow”与正则表达式匹配\ b(\ w + )$(用C表示为“\ b(\ w +)$”)并保留第一个捕获的组,即“黄色”。
答案 4 :(得分:-2)
(重叹)原始代码在标准/ K&amp; R / ANSI C中错误!它不初始化字符串(名为str的字符数组)!如果编译的例子,我会感到惊讶。您的计划细分市场真正需要的是
if strcpy(str, "my cat is yellow")
{
/* everything went well, or at least one or more characters were copied. */
}
或者,如果您承诺不尝试操纵字符串,您可以在源代码中使用指向硬编码“我的猫是黄色”字符串的字符指针。
如上所述,如果“单词”以空格字符或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) )
循环中的而不只是寻找空间......