当前位置:网站首页>[C Supplement] Conversion of Integer to String
[C Supplement] Conversion of Integer to String
2022-07-30 03:03:00 【one reed fly fp】
一、库函数
1.1 atoi字符串转换成int型整数
1.1.1 函数原型
int atoi(const char* str);
- The parameter is the string address to be converted;
- The function returns the converted integer.
1.1.2 函数说明
- 函数返回 int 类型,So for exceeding 10 位的字符串,The conversion is bound to fail, 10Bits can also go wrong,因为 int 的最大值为 2,147,483,647 .
- The function conversion process is:从左到右,Skip whitespace characters first,Find the digit character after the whitespace character,Other non-numeric characters after numeric characters are ignored.If the first non-whitespace character in the string is not a valid integer,或str为空,or contain only whitespace characters,函数返回0
1.1.3 使用举例
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char str1[11] = {
0}, str2[11] = {
0}, str3[11] = {
0}, str4[15] = {
0};
int num1, num2, num3, num4;
strcpy(str1, " 12snd34f.6");
strcpy(str2, " ab12,st");
strcpy(str3, "1111111111");
strcpy(str4, "11111111111");
num1 = atoi(str1);
num2 = atoi(str2);
num3 = atoi(str3);
printf("%d\n%d\n%d\n%d\n", num1, num2, num3, num4);
return 0;
}
输出结果:
(The last bit of data overflowed)
1.1.4 strtol字符串转换成长整型(long)
1.2 itoa整数转换成字符串
1.2.1 函数原型
char* itoa(int value, char* str, int redix);
- itoa 全称 integer to ASCII
- 参数表:
- value:The integer value to convert
- str:The storage address of the converted string
- redix:基数,Represents the base number of an integer
1.2.2 函数说明
itoa函数头文件为stdlib.h;- 如果取10进制,且 value 为负数,A minus sign is added before the conversion result(
-),The rest of the bases are treated as unsigned; - Cardinality means will value Convert to the corresponding base number and then convert to a string.
- Since the function parameter is
int类型,Therefore the converted value cannot exceedint的存储范围. - The character array to be stored also needs to be long enough to hold the converted numeric string;
- The function returns the address of the string.
注意: 与atoi不同,This function is a non-standard library function,为Windows独有,Some compilers may not support this function,To write cross-platform programs,用更为强大的sprintf函数即可,用法举例:sprintf(str, “%x”, 100); 将100以16The base form is converted to a string and stored in str指向的内存区域.
use control:
itoa | sprintf |
|---|---|
itoa(value, str, 10); | sprintf(str, "%d", value); |
itoa(value, str, 8); | sprintf(str, "%o", value); |
itoa(value, str, 16); | sprintf(str, "%x", value); |
1.2.3 使用举例
#include<stdio.h>
#include<stdlib.h>
int main(){
char str[1000] = {
0};
const int mlen = 11; //最高位数
int num = 1;
for(int i=1; i<=mlen; i++){
itoa(num, str, 10); //以10进制转换为字符串
printf("%10s", str);
itoa(num, str, 16); //以16进制转换为字符串
printf(" %s\n", str);
num += pow(10, i);
}
return 0;
}
输出结果:
- On the left is a decimal string,右侧为16进制字符串;
- The last data overflowed,超出 int 存储范围.
二、大数转换
- For the above library functions only int The data in the range is valid,If out of range,other methods are required.
2.1 字符串转换成整数
- For pure numeric strings only,使用最大的long long 类型
#include<stdio.h>
#include<string.h>
long long my_atoi(char* str);
int main(){
char str[20] = {
0};
scanf("%s", str);
long long n = my_atoi(str);
printf("%lld\n", n);
return 0;
}
long long my_atoi(char* str)
{
int i = strlen(str) - 1;
long long result = 0, base = 1, a = 0;
for( ; i>=0; i--){
a = (str[i] - '0')*base; //Multiply each digit by the corresponding number of digits,个位乘1,十位乘10...
result += a;
base *= 10;
}
return result;
}
2.2 整数转换成字符串
char* my_itoa(int n)
{
int tmp_n = n, len = 0; //数字的位数
while(tmp_n){
tmp_n /= 10;
len++;
}
char* result = (char*)malloc(sizeof(char)*(len+1));
if(n == 0) strcpy(result, "0");
else{
for(int i=len-1; i>=0; i--){
result[i] = n%10 + '0';
n /= 10;
}
result[len] = '\0';
}
return result;
}
三、 综合应用 —— 大数相加
题目要求:
Read two numbers as strings,Add and output as a string.
思路:
A bit-by-bit addition method is used,从最低位开始,Convert each character to a number and add them,记录进位的值,Convert the sum of each bit to character storage,Finally, reverse the sequence of characters.
char* solve(char* s, char* t ) {
int i, j;
i = strlen(s) - 1; //从最低位开始
j = strlen(t) - 1;
int max = i>j ? i : j ; //Allocate the character array length,考虑进位,The longest is the highest digit plus1
char* result = (char*)malloc(sizeof(char)*(max + 3));
int len = 0; //The number of digits in the summed value
int sum = 0, add = 0; //各位之和,进位值
//从低到高,逐位相加
while(i>=0 || j>= 0 || add != 0){
int x = i >= 0 ? s[i] - '0' : 0;
int y = j >= 0 ? t[j] - '0' : 0;
sum = x + y + add;
result[len++] = sum % 10 + '0';
add = sum/10;
i--;
j--;
}
//Numeric characters are reversed
for(i=0; 2*i < len; i++){
char tmp = result[i];
result[i] = result[len - i - 1];
result[len - i - 1] = tmp;
}
result[len] = 0;
return result;
}
边栏推荐
- 【ModelArts系列】华为ModelArts训练yolov3模型(训练管理)
- 五种绑定彻底弄懂this,默认绑定、隐式绑定、显式绑定、new绑定、箭头函数绑定详解
- nrm ls 为什么前面不带 *了
- (RCE)远程代码/命令执行漏洞漏洞练习
- JS Bom location 楼层导航效果 offsetTop data-n 方括号选择器
- Answer these 3 interview questions correctly, and the salary will go up by 20K
- JUC (four): five/six states of shorthand thread
- WebSocket在线通信
- HCIP实验(05)OSPF综合实验
- 再度入围|“国产化”大潮来袭,汉得助力乘风破浪!
猜你喜欢

Open address method hash implementation - secondary detection method

JS Navigator appName appVersion userAgent platform

Dell's first pure soft product redefines next-generation object storage

联邦学习综述(二)——联邦学习的分类、框架及未来研究方向

Overview of Federated Learning (1) - Background, Definition and Value of Federated Learning

HCIP OSPF

生死时速,分秒必争

新手入门上位机开发 C#语言:PC串口发送数据

详解轮播图二-通过left定位来轮播图片

音视频开发的正确(学习思路+技术指导)
随机推荐
3.nodejs--modularization
Detailed explanation of carousel picture 2 - carousel pictures through left positioning
【机器学习】通俗易懂决策树(原理篇)
一个塑料瓶的海洋“奇幻漂流”
Mysql中事务是什么?有什么用?
HCIP OSPF
JS Navigator appName appVersion userAgent platform
YOLOv7的一些理解
22/07/21
Oracle超全SQL,细节狂魔
判断Object是否依赖于名叫“XX“的资产
票房破7.9亿美元,最近这部恐龙爽片你看了吗?
matlab之函数
HCIP 第十五天
JUC(四):简记线程的五/六种状态
Hacker News Broadcast | A fake offer steals $625 million
JUC(七):变量的线程安全分析
一本通1922——乒乓球
详解轮播图二-通过left定位来轮播图片
零代码工具推荐---HiFlow