C++ 将字符串中的每个字符转换为 ASCII
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9577182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert each character in string to ASCII
提问by OurFamily Page
Could anyone tell me how to easily convert each character in a string to ASCII value so that I can sum the values? I need to sum the values for a hash function.
谁能告诉我如何轻松地将字符串中的每个字符转换为 ASCII 值,以便我可以对这些值求和?我需要对哈希函数的值求和。
回答by perreal
Each character in a string is already ascii:
字符串中的每个字符都已经是 ascii:
#include <string>
int main() {
int sum = 0;
std::string str = "aaabbb";
for (unsigned int i = 0; i < str.size(); i++) {
sum += str[i];
}
return 0;
}
回答by Carl
To create a hash, you basically only need the integer value of each character in the string and not the ASCII value. They are two very different things. ASCII is an encoding. Your string could be UTF-8 encoded too, which will still mean your string ends with a single NULL, but that each character could take up more than 1 byte. Either way, perreal's solution is the one you want. However, I wrote this as a separate answer, because you do need to understand the difference between an encoding and a storage type, which a char is.
要创建散列,您基本上只需要字符串中每个字符的整数值,而不是 ASCII 值。它们是两个非常不同的东西。ASCII 是一种编码。您的字符串也可能是 UTF-8 编码的,这仍然意味着您的字符串以单个 NULL 结尾,但每个字符可能占用 1 个以上的字节。无论哪种方式,perreal 的解决方案都是您想要的。但是,我将此作为单独的答案编写,因为您确实需要了解编码和存储类型之间的区别,即字符。
It is also probably worth mentioning that with C+11, there is a hash function that is built into the standard library. This is how you would use it.
可能还值得一提的是,在 C+11 中,标准库中内置了一个哈希函数。这就是你将如何使用它。
#include <string>
#include <iostream>
#include <functional>
int main() {
const std::string str = "abcde";
std::cout << std::hash<std::string>()(str) << std::endl;
return 0;
}
Finally, you can still sum the elements of a string without C++11, using std::accumulate:
最后,您仍然可以使用 std::accumulate 在没有 C++11 的情况下对字符串的元素求和:
#include <string>
#include <iostream>
#include <numeric>
int main() {
//0x61+0x62+0x63+0x64+0x65=0x1ef=495
const std::string str = "abcde";
std::cout << std::accumulate(str.begin(),str.end(),0) << std::endl;
return 0;
}
回答by J.N.
Supposing you mean std::string
or char*
, you can sum the characters directly, they are in ASCII representation already (as opposed to Char
in Java or .net). Be sure to use a big enough result type (int
at least).
假设您的意思是std::string
或char*
,您可以直接对字符求和,它们已经以 ASCII 表示(而不是Char
在 Java 或 .net 中)。确保使用足够大的结果类型(int
至少)。
On the other hand, there should be plenty of hash functions for strings in C++ out there, unless this is an excercise, you'd better choose one of those.
另一方面,C++ 中的字符串应该有很多哈希函数,除非这是一个练习,否则你最好选择其中一个。
回答by EricFromChina
Convert it to an int: int(word[x])
将其转换为 int: int(word[x])