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;
}
Yes — in C and C++,
charis just a small integer type (typically with a range from -128 to +127). When you do math on it, it’ll normally be converted tointautomatically, so you don’t even need your cast.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-evaluatedstrlen(s)every iteration, so your linear algorithm just became quadratic instead.Or, if
sis actually astd::string, as the parameter type suggests:As yet one more possibility: