问题描述
将(const char *,size_t)表示的字符串转换为int的最快的方法是什么?
What's the fastest way to convert a string represented by (const char*, size_t) to an int?
字符串不是 null终止。
这两种方式都涉及到我想避免的字符串副本(和更多)。
The string is not null-terminated.Both these ways involve a string copy (and more) which I'd like to avoid.
是的,这个函数被称为几百万次第二。 :p
And yes, this function is called a few million times a second. :p
int to_int0(const char* c, size_t sz)
{
return atoi(std::string(c, sz).c_str());
}
int to_int1(const char* c, size_t sz)
{
return boost::lexical_cast<int>(std::string(c, sz));
}
推荐答案
最快:
int to_int(char const *s, size_t count)
{
int result = 0;
size_t i = 0 ;
if ( s[0] == '+' || s[0] == '-' )
++i;
while(i < count)
{
if ( s[i] >= '0' && s[i] <= '9' )
{
//see Jerry's comments for explanation why I do this
int value = (s[0] == '-') ? ('0' - s[i] ) : (s[i]-'0');
result = result * 10 + value;
}
else
throw std::invalid_argument("invalid input string");
i++;
}
return result;
}
因为在上面的代码中,比较 [0] ==' - ')
是在每次迭代中完成的,我们可以通过在循环中计算 result
然后返回 result
如果 s [0]
确实' - '
,否则返回 -result
(这是一个正数,因为它应该是):
Since in the above code, the comparison (s[0] == '-')
is done in every iteration, we can avoid this by calculating result
as negative number in the loop, and then return result
if s[0]
is indeed '-'
, otherwise return -result
(which makes it a positive number, as it should be):
int to_int(char const *s, size_t count)
{
size_t i = 0 ;
if ( s[0] == '+' || s[0] == '-' )
++i;
int result = 0;
while(i < count)
{
if ( s[i] >= '0' && s[i] <= '9' )
{
result = result * 10 - (s[i] - '0'); //assume negative number
}
else
throw std::invalid_argument("invalid input string");
i++;
}
return s[0] == '-' ? result : -result; //-result is positive!
}
这是一个改进!
在C ++ 11中,你可以使用家庭。还有家庭。
In C++11, you could however use any function from std::stoi
family. There is also std::to_string
family.
这篇关于String(const char *,size_t)to int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!