如何得到一个字符串中从 '\0' 换行字符开始到最右边的空格之间的最后一个单词?例如,我可能会有像这样的东西,其中 str 可以被赋予一个字符串:
char str[80];
str = "my cat is yellow";
我该怎么变成黄色?
像这样:
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
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++;
}
strrchr()
。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) )
在循环中寻找不仅仅是空格....
+ 1
可以在初始化中完成:char *p = strrchr(str, ' ') + 1;
- LihO'\0'
字符。 - Wookie88