簡體   English   中英

使用strstr計數錯誤

[英]incorrect count using strstr

我試圖編寫一個函數,該函數返回字符串中子字符串首次出現的索引。

像在摩天大樓中搜索“ ysc”將返回2。

看起來strstr在做它的工作,因為在while循環之后,它輸出正確的子字符串的第一個char,但是它沒有正確計數並返回正確的int。

我將數組傳遞給函數時可能會設置錯誤,並且在嘗試使用嵌套循環時遇到很多錯誤,因此我嘗試了一個while循環,該循環可以編譯但不能正確輸出。

我對指針並把它們當作爭論還是相當陌生的,所以那里可能存在問題。

任何幫助!

int findSubstring(char *s, char substring[])
{   
    int j = 1;
    char* strPtr = NULL;

    while (strPtr == NULL)
    {
        strPtr = strstr(s, substring);
        if (strPtr != NULL)
            break;
        j++;
    }

    cout << *strPtr << endl;
    cout << "The substring begins at element: " << j << endl;
    return j;
}

您似乎已經使任務復雜化了,因為您使用的是C ++,因此應該使用std::string::find

std::string s = "skyscraper";
std::size_t pos = s.find("ysc");
if( pos != std::string::npos )
    std::cout << "ysc found at " << pos << "\n";
else
    std::cout << "ysc not found" << "\n";

只使用指針算法呢?

int findSubstring(char *s, char substring[])
{   
    char* strPtr = strstr(s, substring);
    if (strPtr != NULL)
    {
        return (int)(strPtr - s);
    }
    else
    {
        return -1;  //no match
    }
}

修正為,請參考以下示例

 int findSubstring(char *s, char substring[]) 
{
    char* pos = strstr(s, substring);
    if(pos) 
     return (int)(pos - s);
    else -1;
}

而且您正在使用C ++,那么,為什么不使用std::string呢?

 int findSubstring(const std::string& s, const std::string& substring)
{   

std::size_t j =s.find(substring);
return ( j!=std::string::npos) ? j :-1;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM