>Maybie你可以建议如何解决我的问题。我正在尝试做这样的事情。我有 2 根字符串。在其中一个中,我有一个包含许多单词的文本,在另一个文本中我有一个字符,例如:B。如果可以制作一个代码,那会找到所有以 B 字符开头的单词?
strtok() 将字符串划分为单词。 一旦你得到第一个字符串中的单词,然后你可以检查每个单词是否以给定的字母开头。 此链接可以为您提供有关如何使用 strtok 的想法。
有许多方法可以使用字符串库函数或使用字符串作为字符数组来执行此操作。 这是我使用 strtok() 告诉的直接方法之一。
你可以使用 strcmp() 函数。它包含在"string.h"标题下。
int strcmp (string 1, string2):此函数比较作为参数传递的两个字符串,并返回 +ve number,0,-ve 编号。
+ve 值表示字符串 1>字符串 2。0 表示字符串 1 和字符串 2 相等-ve 值表示字符串 1
这可能对您有所帮助
#include<stdio.h>
#include<conio.h>
int main()
{
char *str;
char ch;
int i=0,j,count=0,len=0;
clrscr();
puts("Enter String");
gets(str);
puts("Enter Character");
scanf("%c",&ch);
len=strlen(str);
printf("All words that start with character %cnn",ch);
while(str[i]!=' ') //to traverse the string
{
if((i==0)&&str[i]==ch) //for first word
{
j=i;
while(str[j]!=' ')
{
printf("%c",str[j]);
j++;
}
printf(",");
}
if((str[i]==' ')&&(str[i+1]==ch))
{
j=i+1;
while(str[j]!=' '&&j<len) //for all other words
{ //j<len is used only if last word has same character
printf("%c",str[j]);
j++;
}
printf(",");
}
i++;
}
getch();
}