我必须在字符串中搜索子字符串并在每次找到子字符串时显示下面给出的完整单词 -
例如:
Input: excellent
Output: excellent,excellently
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何使输出像上面那样.
我的输出:
excellent,excellently,
Run Code Online (Sandbox Code Playgroud)
它总是给我一个逗号.
Prog:desc迭代地将字典中的每个单词转换为小写,并将转换后的单词存储在较低的单词中.使用strncmp比较input_str和lower的前两个len字符.如果strncmp的返回值为0,则两个字符串的前两个len字符相同.
void complete(char *input_str)
{
int len = strlen(input_str);
int i, j, found;
char lower[30];
found = 0;
for(i=0;i<n_words;i++)
{
for(j=0;j<strlen(dictionary[i]);j++)
{
lower[j] = tolower(dictionary[i][j]);
}
lower[j+1]='\0';
found=strncmp(input_str,lower,len);
if(found==0)//found the string n print out
{
printf("%s",dictionary[i]);
printf(",");
}
}
if (!found) {
printf("None.\n");
} else {
printf("\n");
}
}
Run Code Online (Sandbox Code Playgroud)
在打印第二个单词之前检查您是否已经打印了一个单词:
char printed = 0;
for (i=0; i < n_words; i++)
{
for(j = 0; j < strlen(dictionary[i]); j++)
lower[j] = tolower(dictionary[i][j]);
lower[j + 1] = '\0';
found = strncmp(input_str, lower, len);
if (found == 0)//found the string n print out
{
if (printed)
printf(",");
printf("%s", dictionary[i]);
printed = 1;
}
}
Run Code Online (Sandbox Code Playgroud)