这是一个有关用户输入文本和模式的程序。并使用函数返回模式索引的值。如果找不到模式,请返回-1;由于某些原因,我一直在返回值;
中继续获得-1;这是我的代码:
#include<stdio.h>
#include<string.h>
int contains(const char *text,const char *pattern){
int lengthT,lengthP,i;
int j = 0;
for(i = 0; i < 10; i++){//get the length of pattern
if(pattern[i] == ' '){
lengthP = i;
break;
}
}
for(i = 0;i < 100; i++){//get the length of text
if(text[i] == ' '){
lengthT = i;
break;
}
}
for(i = 0;i < lengthT;i++){
if(text[i] == pattern[0]){
for(j = 1;j <= lengthP + 1;j++){
if(text[i+j] == pattern[j]){
if(j >= lengthP){
return i;
}
continue;
}
}
}
return -1;
}
}
int main(){
const char text[100];
const char pattern[10];
printf("Enter the text: ");
scanf("%s",&text);
printf("Enter the pattern: ");
scanf("%s",&pattern);
printf("Pattern %s occurs in %s at the location %d.n",pattern,text,contains(text,pattern));
return 0;
}
您将return -1;
放置在错误的位置。它应该放置在循环外面遍历文本的循环外,否则如果文本和模式的第一个字母不相同,则功能将直接返回-1。另外,在更正返回语句后,我发现您的逻辑有些错误。
#include<stdio.h>
#include<string.h>
int contains(const char *text,const char *pattern){
int lengthT,lengthP,i;
int j = 0;
lengthP = strlen(pattern);
lengthT = strlen(text);
for(i = 0;i < lengthT;i++){
if(text[i] == pattern[0]){
printf(" f1");
for(j = 1;j <lengthP;j++){
if(text[i+j] == pattern[j]){
if(pattern[j+1]== ' '){
return i;
}
continue;
}
}
}
}
return -1;
}
int main(){
const char text[100];
const char pattern[10];
printf("Enter the text: ");
scanf("%s",&text);
printf("Enter the pattern: ");
scanf("%s",&pattern);
printf("Pattern %s occurs in %s at the location %d.n",pattern,text,contains(text,pattern));
return 0;
}