0
收藏
微博
微信
复制链接

字符串和整数转换如何实现?(附C语言源代码)

2024-04-03 11:12
64

在C语言编程中,字符和整数是极为关键的类型,很多新手经常会遇见字符串和整数之间的转换问题,这种操作一般会出现在读取用户输入、处理文件内容,或者网络通信等,可以说很广泛,所以下面将分步骤介绍如何实现,希望对小伙伴们有所帮助。

image.png

1、字符串转整数的思路

字符串转整数的剧本思路是:遍历字符串中的每个字符,将其对应的数字值累加起来,需要注意的是,需要考虑字符串的正负号、空格及非数字字符。

#include   

#include   

#include   

#include   

#include   

#include   

#include   

  

int my_atoi(const char *str) {  

    int sign = 1, base = 0;  

    while (isspace(*str)) str++; // 跳过空格  

    if (*str == '-') {  

        sign = -1;  

        str++;  

    } else if (*str == '+') {  

        str++;  

    }  

    // 检查溢出  

    if (!isdigit(*str)) {  

        if (*str == '0' && (isdigit(str[1]) || str[1] == 'x' || str[1] == 'X')) {  

            if (str[1] == 'x' || str[1] == 'X') {  

                base = 16;  

                str += 2;  

            } else {  

                base = 8;  

                str += 1;  

            }  

        } else {  

            return 0;  

        }  

    } else {  

        base = 10;  

    }  

    int value = 0;  

    while (isdigit(*str) || (base == 16 && isxdigit(*str))) {  

        if (value > INT_MAX / base) {  

            // 溢出处理  

            if (sign == 1) return INT_MAX;  

            else return INT_MIN;  

        }  

        int digit = (base == 10) ? (*str - '0') : (toupper(*str) < 'A' ? *str - '0' : 10 + toupper(*str) - 'A');  

        value = value * base + digit;  

        str++;  

    }  

    return value * sign;  

}  

int main() {  

    const char *str = "   -42";  

    int num = my_atoi(str);  

    printf("Converted integer: %d\n", num);  

    return 0;  

}

2、整数转字符串

整数转字符串的基本思路是:将整数不断除以10,取余数作为字符串的一位,直到整数位0,然后将得到的字符串反转,即可得到正确的整数表示。

#include   

#include   

#include   

#include   

  

char* my_itoa(int num, char* str, int base) {  

    if (base < 2 || base > 36) {  

        return NULL;  

    }  

    char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";  

    bool isNegative = false;  

    if (num < 0 && base == 10) {  

        isNegative = true;  

        num = -num;  

    }  

    int index = 0;  

    do {  

        str[index++] = digits[num % base];  

        num /= base;  

    } while (num);  

    if (isNegative) {  

        str[index++] = '-';  

    }  

    str[index] = '\0';  

    // 反转字符串  

    for (int i = 0; i < index / 2; i++) {  

        char temp = str[i];  

        str[i] = str[index - i - 1];  

        str[index - i - 1] = temp;  

    }  

    return str;  

}  

int main() {  

    int num = 12345;  

    char str[12];  

    my_itoa(num, str, 10);  

    printf("Converted string: %s\n", str);  

    return 0;  

}

本文凡亿教育原创文章,转载请注明来源!

登录后查看更多
0
评论 0
收藏
侵权举报
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表凡亿课堂立场。文章及其配图仅供工程师学习之用,如有内容图片侵权或者其他问题,请联系本站作侵删。

热门评论0

相关文章

攻城狮之家

专注电子设计,好文分享

开班信息