简体   繁体   中英

how do i convert string like “12345” to int in c using recursion

If I got char* "12345" and I want to convert to int with a recursive function, how can I do that ?

This is a simple way how to convert char to int with loop.

while (str[i]) {
    new_num *= 10;
    new_num += str[i++] - '0';
}

If "rexrsia/rxursia way" means the recursive way, here's one way to do it:

#include <stdio.h>
#include <string.h>

int convert_with_length(char* sz, int cch) {
    // base case: empty string
    if (cch == 0) {
        return 0;
    }

    // recursive case, use the last digit and recurse on the rest:
    // e.g. "12345" becomes 10 * convert("1234") + 5
    return (sz[cch - 1] - '0') + (10 * convert_with_length(sz, cch - 1));
}

int convert(char *sz) {
    return convert_with_length(sz, strlen(sz));
}

int main() {
    char* str = "12345";
    printf("result = %d\n", convert(str));
}

Yet another variant without length calculation:

#include <stdio.h>
int convert_(char* s, int r) {
  return *s ? convert_(s + 1, r * 10 + (*s - '0')) : r;
}
int convert(char* s) {
  return convert_(s, 0);
}
void main()
{
  printf("%d", convert("123456"));
}

I just tried with only one function to convert string to integer may be helpful,

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int strtoint(char *ptr)
{
    int num;
    char *str = NULL;
    if(strlen(ptr) == 0)
        return 0;
    else if(strlen(ptr) == 1)
        return ptr[strlen(ptr)-1]-48;
    else
    {
        str = (char *) malloc(strlen(ptr)-1);
        strcpy(str,ptr);
        str[strlen(ptr)-1]='\0';
        num = (strtoint(str) * 10) + ptr[strlen(ptr)-1]-48;
        free(str);
        return num;
    }
}
int main(void)
{
    printf("converted string %d\n",strtoint("12345"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM