在不使用 Boost 的情况下解析 C++ 中的字符串

parsing a string in C++ without using Boost

本文关键字:C++ 字符串 情况下 Boost      更新时间:2023-10-16
const char* mystring;

在上面的变量中,我将接收值为"ABCD1234"或"abcb1234",我应该解析字符串并获取值 1234(即字符之后(。如何在C++中有效地做到这一点?

我总是在数字前有 4 个单词。

我不应该使用Boost。

不进行错误检查:

const char *c = mystring;
while (*c && ('0' > *c || *c > '9')) ++c;
return atoi(c);

如果需要语法检查,请使用 strtol 而不是 atoi。

字符串的确切模式是什么?

您可以考虑做的一件事是使用字符串方法find_first_not_of()

例如
string newStr = oldStr.substr( oldStr.find_first_not_of( "ABCDabcd" ) );

另一方面,如果你知道你只需要前 4 个字符之后的内容,那真的是一个笨蛋:

string newStr = oldStr.substr( 4 );

您可以使用以下任一方法查找数字序列的开头,因为这两个函数都接受要搜索的多个字符:

  • strpbrk()搜索char*

    char* first_digit = strpbrk(mystring, "0123456789");
    if (first_digit)
    {
        /* 'first_digit' now points to the first digit.
           Can be passed to atoi() or just used as a
           substring of 'mystring'. */
    }
    
  • std::string::find_first_of()

    size_t first_digit_idx = mystring.find_first_of("0123456789");
    if (std::string::npos != first_digit_idx)
    {
        // Use `std::string::substr()` to extract the digits.
    }