使用strstr()函数是错误的

using strstr() function is breaking

本文关键字:错误 函数 strstr 使用      更新时间:2023-10-16

我正在使用strstr()函数,但我正在崩溃。

这部分代码崩溃,错误"读取位置0x0000006c."strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]))

这是完整的代码…

#include "stdafx.h"    
#include <iostream>
#include <string>
void delchar(char* p_czInputString, const char* p_czCharactersToDelete)
{
    for (size_t index = 0; index < strlen(p_czInputString); ++index)
    {
        if(NULL != strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]))
        {
            printf_s("%c",p_czInputString[index]);
        }
    }
}
int main(int argc, char* argv[])
{
    char c[32];
    strncpy_s(c, "life of pie", 32); 
    delchar(c, "def");
    // will output 'li o pi'
    std::cout << c << std::endl;
}

strstr()的原型如下,

char * strstr ( char * str1, const char * str2 );

函数用于从主字符串中定位子字符串。它返回一个指向str1str2第一次出现的指针,或者如果str2不是str1的一部分,则返回一个空指针。

在您的情况下,您正在传递错误的参数给strstr()。你在呼唤,strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]));,是错误的。因为指针p_czCharactersToDelete指向子字符串常量,而p_czInputString指向主字符串。将strstr()调用为strstr(p_czInputString, p_czCharactersToDelete);,并对函数delchar()进行相应的修改。

您正在使用错误的strstr。也许你需要strchrstrpbrk

#include <cstring>
#include <algorithm>
class Include {
public:
    Include(const char *list){ m_list = list; }
    bool operator()(char ch) const
    {
        return ( strchr(m_list, ch) != NULL );
    }
private:
    const char *m_list;
};
void delchar(char* p_czInputString, const char* p_czCharactersToDelete){
    Include inc(p_czCharactersToDelete);
    char *last = std::remove_if(p_czInputString, p_czInputString + strlen(p_czInputString), inc);
    *last = '';
}