gpt4 book ai didi

c++ - 如何使用 strspn 模仿 std::string find_first_not_of

转载 作者:行者123 更新时间:2023-11-30 02:24:56 26 4
gpt4 key购买 nike

我正在尝试创建一个类似于 std::string 的自定义字符串类。

而且我在实现“find_first_not_of”时遇到了麻烦。

这是我的测试代码

#include <iostream>

class String {

private:

char *m_data;
int m_length;

char *alloc(int size);
int length() const {return m_length;}
int size() const {return m_length;}
const char *c_str() const {return m_data;}

public:

String(const char *str=0);

int find_first_not_of(const char *str);
static const int npos;
};

const int String::npos = -1;

char * String::alloc(int size)
{
char * str = new char[size+1];
return str;
}

String::String(const char *str)
{
if (!str) str = "";
m_length = static_cast<int>(strlen(str));
m_data = alloc(m_length);
strcpy(m_data, str);
}

int String::find_first_not_of(const char *str)
{
size_t len = strspn(c_str(), str);

if (len == 0)
return -1;
else
return len;
}

int main(int argc, const char * argv[]) {

String A = "123";
std::string B = "123";

if (A.find_first_not_of("0123456789") == -1)
std::cout << "A is digit" << std::endl;
else
std::cout << "A is not digit" << std::endl;

if (B.find_first_not_of("0123456789") == -1)
std::cout << "B is digit" << std::endl;
else
std::cout << "B is not digit" << std::endl;
return 0;
}

这是我运行代码后看到的结果。

A is not digit
B is digit
Program ended with exit code: 0

有人可以指出我所缺少的吗?

谢谢!

最佳答案

您将 String::find_first_not_ofstd::string::find_first_not_of 混淆了。它们是具有不同功能的不同函数。

我真的不明白 String::find_first_not_of 需要做什么,但这是它们每个返回的内容(一个是字符串的长度,另一个是位置):

std::string::find_first_if_not(来自 here):

The position of the first character that does not match. If no such characters are found, the function returns string::npos.

strspn(来自 here):

The length of the initial portion of str1 containing only characters that appear in str2. Therefore, if all of the characters in str1 are in str2, the function returns the length of the entire str1 string, and if the first character in str1 is not in str2, the function returns zero.

所以即使是函数的内部工作也是不同的。

您应该能够根据此信息进行关注。

关于c++ - 如何使用 strspn 模仿 std::string find_first_not_of,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44997822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com