1

我必须为在字符串中找到子字符串的赋值编写一些代码。

这是我的代码,我添加了注释:

// the target is the substring that we want to find in the source string
// m is the length of the target, and n is the length of the source
int contains(char target[], int m, char source[], int n) {
int flag = 0; // the source originally does not contain the target
int i;

    // go through each character of the source string
for(i = 0; i < n; i++) {
    int targetIndex = 0;
    int j;

            // check if the preceding characters of the source string are a substring
            // that matches the target string
    for(j = i; j < n && targetIndex < m; j++) {
        if(target[targetIndex] == source[j]) {
            flag = 1;
            targetIndex += 1;
        }
        else {
            flag = 0; // a letter does not match
            break;
        }
    }
}

return flag;

}

所以当我测试这个方法时,我总是被0退回,我不明白为什么。
如果我尝试int i = contains("potatoes", 8, "toes", 4);它会给0.
我试过放一些打印语句来查看它匹配的字符,它似乎只找到第一个字母"t"

4

3 回答 3

1

for当你有比赛时,你需要打破外部。

你的代码的工作方式,你可能会找到一个匹配,然后再次运行外循环并“忘记”它。

于 2013-10-12T14:49:50.343 回答
1

试试这样:

for(i = 0; i < n; i++) {
    int targetIndex = 0;
    int j;

            // check if the preceding characters of the source string are a substring
            // that matches the target string
    for(j = i; j < n && targetIndex < m; j++) {
        if(target[targetIndex] == source[j]) {
            flag = 1;
            targetIndex += 1;
        }
        else {
            flag = 0; // a letter does not match
            break;
        }
    }
  if(flag == 1)  
  {
   break;
  }
}

您可以尝试使用 C 的strstr函数,这将使您的事情变得更容易。

例子:

char *x= "Find the substring in this string";
char *y= "substring";
if(strstr(x, y) != NULL) {
    return true;
}
于 2013-10-12T14:51:23.903 回答
0

使用解释性注释对您的代码进行一些修改。

// the target is the substring that we want to find in the source string
// m is the length of the target, and n is the length of the source
int contains(char target[], int m, char source[], int n) {
int flag = 0; // the source originally does not contain the target
int i;

    // go through each character of the source string
for(i = 0; i < n; i++) {
    int targetIndex = 0;
    int j;

            // check if the preceding characters of the source string are a substring
            // that matches the target string
    for(j = i; j < n && targetIndex < m; j++) {
        if(target[targetIndex] == source[j]) {
            targetIndex += 1;
            if(targetIndex == m) { // the 'target' has been fully found
                flag = 1;
                break;
            }
        }
        else
        {
            break;
        }
    }
    if(flag == 1)  // 'target' is already found, no need to search further
    {
      break;
    }
}

return flag;
}

完全找到子字符串后,打破内循环和外循环。

已编辑:此外,int i = contains("potatoes", 8, "toes", 4);它应该是int i = contains("toes", 4, "potatoes", 8);- 而不是 - 根据您的功能描述。

于 2013-10-12T14:59:48.993 回答