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

标签 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;
}

最佳答案

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

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

关于c - 在字符串中搜索子字符串时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28710181/

相关文章:

c - 家庭作业的段错误。不知道为什么

c++ - 尝试输入结构 vector 内的结构成员会导致段错误

c++ - 什么时候保证段错误?

javascript - javascript中的匹配和替换子字符串问题

c - 如何判断HTTP数据包中 "Content-Length: "的长度

从一组单元测试中组成一个组合测试套件程序

html - 在索引处的字符串中插入字符串(快速)

swift - 在 Swift 中分隔字符串

c - C 语言的目录列表程序

c - 通过引用将一个 vector (数组)的值设置为另一个 vector (数组)的值