遍历C字符串:获取字符串的最后一个单词

你怎么会得到一个字符串的最后一个字,从’\ 0’换行符到最右边的空格? 例如,我可以在这样的地方为str分配一个字符串:

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

我怎么会变黄?

像这样的东西:

 char *p = strrchr(str, ' '); if (p && *(p + 1)) printf("%s\n", p + 1); 

我会使用函数strrchr()

如果您不想使用’strrchr’function,这是解决方案。

 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++; } 

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

(重叹)原始代码在标准/ 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) ) 

在循环而不是寻找一个空间….