您提取了此语句中的第一个单词
const char *token = strtok_s(testString, ", ", &context);
但你没有打印出来。在循环中先前调用 strtok_s 之后,您开始在 while 循环中打印单词。
您需要两个指向相邻提取字符串的指针,并使用这些指针可以比较字符串的第一个字母。
这是一个演示程序(为简单起见,我使用 strtok 而不是 strtok_s)
#include <stdio.h>
#include <string.h>
int main(void)
{
char testString[] = "In the end, we will remember not the words "
"of our enemies, but the silence of our friends";
char *first_word = NULL;
char *second_word = NULL;
const char *delim = ", ";
if ( ( first_word = strtok( testString, delim ) ) != NULL )
{
while ( ( second_word = strtok( NULL, delim ) ) != NULL &&
*first_word != *second_word )
{
first_word = second_word;
}
}
if ( second_word != NULL )
{
printf( "%s <-> %s\n", first_word, second_word );
}
return 0;
}
程序输出是
we <-> will
如果你想输出所有这样的单词对,那么程序可以如下所示
#include <stdio.h>
#include <string.h>
int main(void)
{
char testString[] = "In the end, we will remember not the words "
"of our enemies, but the silence of our friends";
char *first_word = NULL;
char *second_word = NULL;
const char *delim = ", ";
if ( ( first_word = strtok( testString, delim ) ) != NULL )
{
while ( ( second_word = strtok( NULL, delim ) ) != NULL )
{
if ( *first_word == *second_word )
{
printf( "%s <-> %s\n", first_word, second_word );
}
first_word = second_word;
}
}
return 0;
}
程序输出是
we <-> will
of <-> our
of <-> our
但是,与其使用strtok 或strtok_s,不如使用基于函数strspn 和strcspn 的方法要好得多。在这种情况下,您可以处理常量字符串。