我刚开始用C语言编程,并决定编写一个函数来搜索字符串中的子字符串来测试自己(是的,我知道已经有了一个函数)。但是,该计划有时会给出正确的'回答但有时也会给出看似毫无意义的数字。这与我使用printf有什么关系吗?在此先感谢:)。
#include <stdio.h>
int check_char_exists(char fvar_string[],char fvar_chartosearchfor);
int check_string_exists(char fvar_string[],char fvar_stringtosearchfor[]);
int main() {
char ctring[] = {'A','B','C','D','E','F','G'};
char ctringtosearchfor[] = {'D','E','F'};
check_string_exists(ctring,ctringtosearchfor);
return 0;
}
int check_char_exists(char fvar_string[],char fvar_chartosearchfor) {
int fvar_hits = 0;
for (int foo = 0; foo < (sizeof(fvar_string) / sizeof(char)); foo ++) {
if (fvar_string[foo] == fvar_chartosearchfor) {
fvar_hits += 1;
}
}
return fvar_hits;
}
int check_string_exists(char fvar_string[], char fvar_stringtosearchfor[]) {
int fvar_stringtosearchfor_size;
int a;
int fvar_string_size;
int b;
int subhits;
int hits;
//Get length of string to be searched
while (b != NULL) {
b = fvar_string[fvar_string_size];
fvar_string_size++;
}
//Get length of string to search for
while (a != NULL) {
a = fvar_stringtosearchfor[fvar_stringtosearchfor_size];
fvar_stringtosearchfor_size++;
}
for (int foo; foo < fvar_string_size; foo ++) {
if (fvar_string[foo] == fvar_stringtosearchfor[0]) {
for(int bar = 0; bar < fvar_stringtosearchfor_size;bar++) {
//If both are equal add to subhits
if(fvar_string[foo + bar] == fvar_stringtosearchfor[bar]) {
subhits +=1;
}
//If subhits equal to length of string to search for add 1 to hits
if (subhits == (fvar_stringtosearchfor_size - 1)) {
hits += 1;
}
}
subhits = 0;
}
}
printf("%d",hits);
}
编辑:对不起,这是输出
2user@PC:~$ ./file
2user@PC:~$ ./file
2user@PC:~$ ./file
1869833334user@PC:~$ ./file
2user@PC:~$ ./file