我必须为一个在字符串中找到子字符串的赋值编写一些代码。
这是我的代码,我添加了评论:
// 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"
。
答案 0 :(得分:1)
当你有匹配时,你需要打破外部for
。
您的代码的工作方式,您可能会找到匹配项,然后再次运行外部循环并“忘记”它。
答案 1 :(得分: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;
}
答案 2 :(得分: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;
}
完全找到子字符串后,断开内部和外部循环。
EDITED:
另外,根据您的功能说明,而不是int i = contains("potatoes", 8, "toes", 4);
,它应该是int i = contains("toes", 4, "potatoes", 8);
。