我似乎在编写字符串搜索功能时遇到问题.strlength和strmid都是以前编写的功能,已经过测试并且正在工作.
int strfind(char * string1, char * string2)
{
/* if string1 contains the substring string2 returns
the starting position of string2 in string1
otherwise returns -1
e.g. strinc("hello world","wor") returns 6
strinc("hello world","war") returns -1
*/
int begPos = 0, endPos, count = 0, match = 1;
char *tempStr;
endPos = strlength(string2)-1;
while (endPos <= strlength(string1)-1)
{
strmid(string1, begPos, endPos, tempStr);
while (match == 1)
{
if (tempStr[count] == string2[count]) {
if (count < strlength(string2)) count++;
else break;
}
else match = 0;
}
if ( match == 1 ) return begPos;
else { begPos++;
endPos++; }
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
算法应该是这样的
我遇到的问题是
while (match == 1)
{
if (tempStr[count] == string2[count]) {
if (count < strlength(string2)) count++;
else break;
}
else match = 0;
}
Run Code Online (Sandbox Code Playgroud)
似乎永远不会达到else条款.返回的值似乎总是begPos初始化的值.这是一个家庭作业,但我已经使用不同的方法重写了几次,例如for循环,并做了多次干运行,似乎无法解决问题.任何你可以流下的灯都会非常感激.
干杯,
espSquall
strmid功能
void strmid(char * string1, int start, int end, char * string2)
{
/* copies the elements of string1 from start to end
to string2 */
int len, count2 = 0;
for (len = start; len <= end; len++)
{
string2[count2] = string1[len];
count2++;
}
string2[count2] = '\0';
}
Run Code Online (Sandbox Code Playgroud)
我只有一点要提出来.
您如何认为这tempStr是有用的?
该行将其char *tempStr;设置为当时堆栈上发生的任何事情,而C缺少"正确"的引用传递,无法通过调用更改它:
strmid(string1, begPos, endPos, tempStr);
Run Code Online (Sandbox Code Playgroud)
要更改指针,您必须传入&tempStr而不是传入tempStr.
所以,在我看来,你tempStr并没有指出任何可用的东西.
而且,根据您添加的strmid功能,该程序肯定是在"未定义的行为"类中.快速修复,虽然kludgy,将改变:
char *tempStr;
Run Code Online (Sandbox Code Playgroud)
至:
char tempStr[1000];
Run Code Online (Sandbox Code Playgroud)
这可能无法解决您的所有问题(并且它会引入缓冲区溢出的可能性),但它至少会为您提供一个定义良好的程序.