Home > Mobile >  convert a string cointaing a base 10 number to an integer value
convert a string cointaing a base 10 number to an integer value

Time:10-12

I am fairly new to programming and I am trying to convert a string containing a base 10 number to an integer value following this pseudo algorithm in c.

start with n = 0
read a character from the string and call it c 
if the value of c is between '0' and '9' (48 and 57):
   n = n * 10  (c-'0')
   read the next character from the string and repeat
else return n

here is the rough basics of what i wrote down however I am not clear on how to read a character from the string. i guess im asking if i understand the pseudocode correctly.

stoi(char *string){
  int n = 0;
  int i;
  char c;
  for (i = 0;i < n ; i  ){
      if (c[i] <= '9' && c[i] >= '0'){
          n = n *10  (c - '0')}
      else{
           return n
           }
  }
}

CodePudding user response:

Congrats on starting your C journey!

One of the most important aspects of strings in C is that, technically, there are none. A string is not a primitive type like in Java. You CAN'T do:

String myString = "Hello";

In C, each string is just an array of multiple characters. That means the word Hello is just the array of [H,e,l,l,o,\0]. Here, the \0 indicates the end of the word. This means you can easily access any character in a string by using indexes (like in a normal array):

char *myString = "Hello";
printf("%c", myString[0]); //Here %c indicates to print a character

This will then print H, since H is the first character in the string. I hope you can see how you can access the any character in the string.

CodePudding user response:

You were close, you just need to traverse the string to get the value of each digit.

Basically you have two ways to do it.

Using array notation:

int stoi(const char *str)
{
    int n = 0;

    for (int i = 0; str[i] != '\0'; i  )
    {
        char c = str[i];

        if ((c >= '0') && (c <= '9'))
        {
            n = n * 10   (c - '0');
        }
        else
        {
            break;
        }
    }
    return n;
}

or using pointer arithmetic:

int stoi(const char *str)
{
    int n = 0;

    while (*str != '\0')
    {
        char c = *str;

        if ((c >= '0') && (c <= '9'))
        {
            n = n * 10   (c - '0');
        }
        else
        {
            break;
        }
        str  ;
    }
    return n;
}

Note that in both cases we iterate until the null character '\0' (which is the one that marks the end of the string) is found.

Also, prefer const char *string over char *string when the function doesn't need to modify the string (like in this case).

  • Related