-->

Convert each character in string to ASCII

2020-07-23 03:49发布

问题:

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.

回答1:

Each character in a string is already 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;
}


回答2:

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.

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.

#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:

#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;
}


回答3:

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).

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.



回答4:

Convert it to an int: int(word[x])



标签: c++ string ascii