在C ++中将字符转换为整数

编程入门 行业动态 更新时间:2024-10-25 02:28:15
本文介绍了在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 ++中将字符转换为整数

本文发布于:2023-10-24 16:51:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524486.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   转换为   中将   字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!