gpt4 book ai didi

c - 我需要知道一个字符串在另一个字符串中出现了多少次!使用C

转载 作者:行者123 更新时间:2023-11-30 19:59:05 25 4
gpt4 key购买 nike

嗯,标题已经说明了我需要的内容。我尝试使用循环,但效果不佳,所以我来寻求你们的帮助!

这是我的代码:

#include <stdio.h>
#include <stdlib.h>


int main()
{
char word[31], word2[31];
int size1, size2;
int i, j, k; // control
int count = 0;

printf ("\nInput the first word");
scanf ("%s", word);
printf ("\nInput the second word: ");
scanf (" %s", word2);

// I tried to make a loop through the first string and if it matches a letter, it would loop through the others (if they are equal, we have a substring), but failed to put it on the `for` loop


printf ("'%s' appears %d times within '%s'", word2, count, word);

return 0;
}

最佳答案

strstr是一个有用的函数,它大大缩短了您的代码;当您找到匹配项时,只需使用字符串的其余部分重试即可;

#include <string.h>
#include <stdio.h>

int main()
{
const char* source = "aabaa";
const char* string2find = "aa";

int occurrences;
const char *ptr, *lastfind = NULL;

for(ptr=source; (lastfind=strstr(ptr, string2find)); ptr=lastfind+1)
occurrences++;

printf("%d\n", occurrences);

return 0;
}

...或者,如果您确实决定不使用 string.h 函数来执行此操作,则代码会变得更加冗长;

#include <string.h>
#include <stdio.h>

int main()
{
const char* source = "aaabaa";
const char* string2find = "aa";

int count=0;
const char *position;
for(position=source; *position; position++) {
int comparepos, equal=1;
for(comparepos=0; string2find[comparepos]; comparepos++) {
if(position[comparepos] != string2find[comparepos]) {
equal = 0;
break;
}
}
count+=equal;
}

printf("%d\n", count);

return 0;
}

关于c - 我需要知道一个字符串在另一个字符串中出现了多少次!使用C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14801155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com