-4
const char* mystring;

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

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

我不应该使用Boost。

4

3 回答 3

1

没有错误检查:

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

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

于 2012-07-13T10:42:54.433 回答
1

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

您可能会考虑做的一件事是使用字符串方法,find_first_not_of()例如

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

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

string newStr = oldStr.substr( 4 );
于 2012-07-13T10:43:10.610 回答
1

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

  • 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.
    }
    
于 2012-07-13T10:43:33.713 回答