当我不使用标准字符串时,如何在 c++ 中将字符串转换为 int?

How can I convert a string to an int in c++ when I'm not using a standard string?

本文关键字:字符串 c++ 转换 int 标准      更新时间:2023-10-16

我正在构建自己的字符串类,我正在尝试使用此函数将数字字符串转换为整数:

int String::convertToInt() const {  
    int exp = length() - 1;
    int result = 0;
    for(int i = 0; i < length(); ++i) {
        result += (charAt(i) - '0') * (10 ^ exp);
        --exp;
    }   
    return result;
}

有些东西工作不正常,但我无法挑选出它是什么。当我尝试将"49"转换为 int 时,它会将其转换为 134。

^是XOR。我相信你正在寻找std::pow(10, exp).

甚至这个:

int String::convertToInt() const {  
    int order = std::pow(10, length() - 1);
    int result = 0;
    for(int i = 0; i < length(); ++i) {
        result += (charAt(i) - '0') * order;
        order /= 10;
    }   
    return result;
}

最简单的方法是意识到494 * 10 + 9493同样是49 * 10 + 3

也就是说,结果是前 N-1 位数字加上最后一位数字的 10 倍。您可以将其编写为循环或递归函数。堆栈深度不会伤害您;大约 20 位后,您甚至会溢出 64 位的结果。所以

int String::convertToInt() const {
    if (empty()) return 0; // Recursive functions better terminate.
    // TODO: negative numbers.  
    return 10 * convertToInt(substr(0, length()-1)) + (back() - '0');
}

int String::convertToInt() const {
    // TODO: negative numbers.  
    int result = 0;
    for(int i = 0; i < length(); ++i) {
        result * = 10;
        result += (charAt(i) - '0');
    }   
    return result;
}

更有效的方法是:

// I know you said you are using something else
// but the same principle applies here
std::string s = "12345";
unsigned int result = 0;
unsigned int place = 1;
for (std::size_t i = s.length() - 1; i >= 0; --i, place *= 10)
{
    result += (s[i] - '0') * place;
}

基本上,你从最右边的角色开始,然后向左工作。 你向左移动的每个字符,你把你的place乘以 10(非常类似于我们大多数人在成长过程中学会做加法的方式:加上你的 1 ......添加您的 10 年代 ...添加您的 100 个 ...等)。 这也假设您已经知道字符串只包含数字字符 ('0'-'9')。