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++, 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.
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];
Or, if s
is actually a std::string
, as the parameter type suggests:
for (int i=0; i<s.size(); i++)
Sum += s[i];
As yet one more possibility:
Sum = std::accumulate(s.begin(), s.end(), 0);
Characters are usually represented internally by integers, so s[i]
can be assigned to an integer.
If you have char '1'
, and want to store int 1
, then you can do s[i]-'0'
.
You might be looking for
Sum += s[i] - '0';
For the general case of converting numbers to strings and vice versa see this FAQ entry.
The function youre looking for is sscanf.
You find it in the header stdio.h
and it's defined like this
int sscanf ( const char * str, const char * format, ...);
In your case you would use it like this:
string str = "SomeStringWithNumbers";
int s, len;
len = str.length();
for(int i = 0; i < len; i++ )
{
int status = sscanf( str[i], "%d", &s);
// Check status if necessary
}
If your string does not only consist of your desired integeer you need to adapt the parameters. You can then modify the first parameter so it points directly to the part of the string where your number lies or you must adapt the format string. Also you should check the return value then.
You can use strtol or, since this was tagged C++, a string stream.
string myStream = "45";
istringstream buffer(myString);
int value;
buffer >> value;
And the answer is (i think)
int i = atoi("5")
Btw atoi stance for ascii to Integer.
Accoarding to Cat Plus Plus atoi isn't supported probably. So you better don't use it then ;)