C语言查找字符串中某字符第几次出现的位置

2025-01-04 14:26:09
推荐回答(4个)
回答1:

#include
#include
int main()
{
    char s[1024];
    gets(s);
    int len = strlen(s), i, index = -1;
    for(i = 0; i < len - 3; i++)
    {
        if(s[i] == 'f' && s[i + 1] == 'o' && s[i + 2] == 'r')
            index = i;
    }
    printf("%d\n", index);
    return 0;
}

回答2:

#include 
#include
using namespace std;
int main()
{
string a="this is java for you,java is good for programming!";
int len=a.length();
for(int i=len-1;i>=0;i--)
{
if(a[i]=='r'&&a[i-1]=='o'&&a[i-2]=='f')
{

cout< break;
}
}
return 0;
}

回答3:

#include
#include
#include
#include
int main()
{
int n,i,j,b[51]={0};
char a[]={"this is java for you,java is good for programming!"};
n=strlen(a);
for(i=0;i {
if(a[i]=='f'&&a[i+1]=='o'&&a[i+2]=='r')
{
b[i]=1;
}

}
for(i=0;i<51;i++)
{
if(b[i]==1)
{
j=i;
}
}
printf("%d",j);

}

回答4:

#include
#include

main()
{
int i,index = -1;
char s[] = "this is java for you,java is good for programming!";
char* cp = s;
for(i = 0;i < strlen(s) - 2;i++)
{
if(*(cp + i) == 'f' && *(cp + i + 1) == 'o' && *(cp + i + 2) == 'r' && i > index)index = i;
}

if(index != -1)printf("最后一次出现字符串'for'的位置为%d\n",index);
else printf("没有找到字符串'for'");
}