2

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;
}
OurFamily Page
  • 233
  • 2
  • 6
  • 9
  • 5
    `strlen(std::string)`? Say what? – trojanfoe Mar 06 '12 at 22:45
  • Something like that, yes. You should look up the string class though to find out how to correctly get the length. – Joachim Isaksson Mar 06 '12 at 22:46
  • have you had a look at [this](http://en.wikipedia.org/wiki/List_of_hash_functions) before you've started to make up your own hash function? – moooeeeep Mar 06 '12 at 22:59
  • @moooeeeep: Obviously this is homework. OP, your teacher may very well teach you to write code like this as you are a beginner, but be aware that this would not be considered production quality code by most C++ teams. – Ed S. Mar 06 '12 at 23:18
  • yes. I am kind of figuring that. But the thing is I am given some code. and told to add to it. so i cant just do whatever I want. – OurFamily Page Mar 07 '12 at 01:10
  • 2
    Duplicate of [Convert char to int in C and C++](https://stackoverflow.com/questions/5029840/convert-char-to-int-in-c-and-c) (second interpretation) – user202729 Sep 02 '21 at 14:41

6 Answers6

13

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);
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • +1 `std::accumulate()` -- "you really don't want to use `strlen(s)` inside the stopping condition for your for-loop" IME compilers are smart enough to figure out if they can lift that out of the loop most of the time. – bames53 Mar 06 '12 at 23:18
  • @bames53: doing a bit of updated testing, I find gcc doing the loop hoisting, but VC++ not. – Jerry Coffin Mar 07 '12 at 02:57
6

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

prelic
  • 4,450
  • 4
  • 36
  • 46
3

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.

Community
  • 1
  • 1
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
0

You can use strtol or, since this was tagged C++, a string stream.

string myStream = "45";
istringstream buffer(myString);
int value;
buffer >> value; 
Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • No, don't use `atol`. `strtol`, if you really must, but for hashing purposes you might as well not convert at all. – Cat Plus Plus Mar 06 '12 at 22:47
  • @CatPlusPlus: Yeah you're right. I forgot that you essentially cannot check for failure as it returns 0... – Ed S. Mar 06 '12 at 23:02
  • Cat Plus Plus. But our exercise is to convert them into ascii and then sum the ascii and then divide modulo something. Is there a name for that type of hash function? – OurFamily Page Mar 06 '12 at 23:17
0

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.

Toby
  • 3,815
  • 14
  • 51
  • 67
-1

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

Nactive
  • 540
  • 1
  • 7
  • 17