'\ 0'改行文字から右端のスペースまで、文字列の最後の単語をどのように取得しますか?たとえば、strに文字列を割り当てることができるようなものを作成できます。
char str[80];
str = "my cat is yellow";
どうすれば黄色になりますか?
このようなもの:
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 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++;
}
関数を使いますstrrchr()
これを行う最良の方法は、既存のソリューションを利用することです。(はるかに一般的な問題に対する)そのような解決策の1つは、Cのオープンソース正規表現ライブラリであるPerl互換正規表現です。したがって、文字列「my catisyellow」を正規表現\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) )
スペースだけを探すのではなく、ループで....