如何在字符串中搜索子字符串时返回指针位置?

时间:2014-09-26 16:22:25

标签: c++

请帮助我们如何完成功能。 我得到exersize for develop函数用于在字符串中搜索子字符串并返回enter的第一个位置。 这就是我所做的代码:

int strstr(const char *str, const char *pattern) {
const char *st = str; // assign adress of string to pointer
const char *pa = pattern; //assign adress of pattern what we must find in string to pointer
while (*st){ // starting sort out string
    ++st;
    if( *st == *pa){ //when first symbol of pattern equal to symbol of string starting the loop
        int i = 0; //counter of iteration for possibility to return first enter of substring

        for(i;*st == *pa;i++){ //that loop sort out every next symbol of string and pattern for equality
            ++st;
            ++pa;
        } //loop finish when pattern or string was ended, or any next symbol was not equal

        if(*pa == 0){ //if patter was ended return position of first enter
            return st-i; //there not compiling((
        }

        pa-i; //reset pattern
        st-i; //reset string
    }
}
return -1; //return -1, if substring was not find
}

对于运气不好的代码没有编译...错误是从'const char *'无效转换为'int' 什么类型必须变量i为此?请检查我的逻辑)

3 个答案:

答案 0 :(得分:0)

return st-i; //there not compiling(( 

您正在返回一个指向常量char的指针,您的函数需要返回一个整数。我最好的猜测是你需要把它变成:

return *(st-i) 

使用*将指针取消引用到const char对象中,该对象可与int

互换

答案 1 :(得分:0)

问题是您的函数是currentlu定义为返回int

如果您希望返回int,例如字符串开头的相对位置,那么您必须返回指针之间的差异

return (st-i)-str;    // st-i = begin of the pattern found,  - str for the relative position 

如果您想要返回一个指针,那么您的功能签名将会被更改,当您没有完成时,您应该返回nullptr而不是-1拍打。

其他一些小问题:

  • 在开始比较风险之前递增st如果字符串以字符串开头,则错过该模式。
  • pa-ist-i没有效果:它只是表达式,不存储任何更改。也许你想写pa-=i

答案 2 :(得分:0)

尝试以下方法。至少它看起来更简单。:)

#include <iostream>

int strstr( const char *str, const char *pattern )
{
    bool found = false;
    const char *p = str;

    for ( ; *p && !found; ++p )
    {
        size_t i = 0;
        while ( p[i] == pattern[i] && pattern[i] != '\0' ) ++i;
        found = pattern[i] == '\0';
    }

    return found ? --p - str : -1;
}

int main() 
{
    std::cout << ::strstr( "Hello evsign", "evsign" ) << std::endl;

    return 0;
}

输出

6

至于你的代码,那么即使循环中的第一个语句也是错误的

while (*st){ // starting sort out string
    ++st;

为什么st会增加?

也是这个循环

for(i;*st == *pa;i++){ 

应写为

for( ;*st == *pa && *pa; i++){