在字符串中搜索子字符串时出现分段错误

时间:2015-02-25 02:39:53

标签: c segmentation-fault substring

我试图编写一个检查字符串以查看它是否包含子字符串的方法。因此,例如,如果用户输入是“hello”并且他们在字符串中搜索“lo”,则输出将为“true”,但如果他们搜索“ol”,则输出将为“false”。这是为了一个班级(我不是在寻找有人为我做这个)所以我应该手工完成并且不使用许多内置函数。现在我的代码编译然后给我一个分段错误:11。

void subsetCheck(char *string, char *srch){
    char str[100];
    char search[100];
    strcpy(str, string);
    strcpy(search, srch);
    int i = 0, j = 0, flag = 0; 
    while(i < strlen(str)){
        if(strcmp(str[i],search[j]) == 0){
            for(j; j < strlen(search); j++){
                if(strcmp(str[i],str[j]) != 0){
                    j = 0;
                    break;
                }
                else{
                    flag = 1;
                }
            }
        }   
    i++;
    }
    if(flag == 1){
        printf("TRUE");
    }
    else{
        printf("FALSE");
    }
return;
}

我编辑了我的代码,其中包含了评论中提到的一些内容,并重新安排了一些for循环,并在评论中添加了试图解释我认为我在每一步所做的事情。

void subsetCheck(char *string, char *srch){
    char str[100];
    char search[100];
    strcpy(str, string);
    strcpy(search, srch);
    int i = 0, j = 0, flag = 0, k = 0;
    while(i < strlen(str)){
        for(j; j <= strlen(search);j++){ //for length of the substring during each i iteration 
                if(str[i] == search[j]){ //if position i matches first letter in substring go into for loop
                    for(k; k <= strlen(search);k++){ //create variable k to allow iteration through strin without messing up placement of i, incase entire substrin isnt there
                        k = i;
                    if(str[k] != search[j]){ //if string position k doesnt equal position j, reassign both variables and break out of the loop
                        j = 0;
                        k = i;
                        flag = 0;
                        break;
                    }
                    else{ //if it does than assign flag the value of 1 and iterate both variables
                        flag = 1;
                        j++;
                        k++;
                    }
                }
            }
        }   
    i++;
    }
    if(flag == 1){
        printf("TRUE");
    }
    else{
        printf("FALSE");
    }
return;
}

1 个答案:

答案 0 :(得分:0)

    if(strcmp(str[i],search[j]) == 0){

str[i]search[j]已经是单个字符。您应该使用比较运算符而不是strcmp()来比较字符。

相关问题