在C ++中将字符转换为整数 [英] Convert a character to an integer in C++

查看:165
本文介绍了在C ++中将字符转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将字符串中的每个字符设置为整数?这只是我为了写一个散列函数要做的第一件事。我必须将字符串中的每个字符设置为一个整数,以便我可以对它们的值求和。请帮忙!它是这样的东西

How can I set each character in a string to an integer? This is just the first thing I have to do in order to write a hash function. I have to set each character in a string to an integer so that I can sum their values. Please help! It it something like this??

    int hashCode(string s)
{
   int Sum = 0;
   for(int i=0; i<strlen(s); i++)
   {
      Sum += (int)s[i];
   }
   return Sum;
}


推荐答案

C ++, char 只是一个小整数类型(通常范围为-128到+127)。当你做数学时,它通常会自动转换为 int ,所以你甚至不需要你的演员。

Yes -- in C and C++, char is just a small integer type (typically with a range from -128 to +127). When you do math on it, it'll normally be converted to int automatically, so you don't even need your cast.

另外,你真的不想在for循环的停止条件中使用 strlen(s)。至少对于大多数编译器,这将强制它每次迭代重新评估 strlen(s),所以你的线性算法只是变成二次方程。

As an aside, you really don't want to use strlen(s) inside the stopping condition for your for-loop. At least with most compilers, this will force it to re-evaluated strlen(s) every iteration, so your linear algorithm just became quadratic instead.

size_t len = strlen(s);

for (int i=0; i<len; i++)
    Sum += s[i];

或者,如果 s code> std :: string ,作为参数类型建议:

Or, if s is actually a std::string, as the parameter type suggests:

for (int i=0; i<s.size(); i++)
    Sum += s[i];

还有一种可能性:

Sum = std::accumulate(s.begin(), s.end(), 0);

这篇关于在C ++中将字符转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆