C++ 11字符数组/字符串/数字转换/字符串拼接

本文介绍了C++中数字与字符串之间的转换方法,包括int、float、double等类型的转换,并详细讲解了使用stringstream、atoi/atof/stoi/stod等函数进行转换的过程。此外,还涉及了char数组与string之间的转换及字符串拼接的方法。

一、num转string

头文件

#include<string>
#include<typeinfo>

1.1 int型数字转字符串

int num = 123;
string num2str = to_string(num);
cout << typeid(to_string(num) == typeid(string) << endl;  // true

1.2 float/double型数字转字符串(不补0)

头文件

#include<sstream>
double num = 123.56;  // float同理
stringstream sstream;
sstream << num;
string num2str = sstream.str();  // num2str = "123.56"
cout << typeid(sstream.str() == typeid(string) << endl;  // true
sstream.clear();  // 若在用一个流中处理大量数据,则需手动清除缓存,小数据或不同流可忽略

缺点处理大量数据转换速度较慢stringstream不会主动释放内存,如果要在程序中用同一个流,需要适时地清除一下缓存,用stream.clear()

二、string转num

2.1 使用stringstream类处理

  • 字符串转int/float/double型数字(不补0)
string str = "456.78";
double num;        // float同理,int需要str为整数,否则报错
stringstream sstream(str);
sstream >> num;    // num = 456.78
cout << typeid(num == typeid(double) << endl;  // true

2.2 使用<string>处理

头文件

#include<string>
string str = "456.78";
double num = stod(str);   // num = 456.78    
cout << typeid(num == typeid(double) << endl;  // true

下面给出常用的转换方法,完整转换方法请见《C++中的字符串(String)和数值转换》

转换数字的类型默认完整参数功能全参例子
intstoi(s)stoi(s,p,b)把字符串s从p开始转换成b进制的intstoi(s, 0, 10)
floatstof(s)stof(s,p)把字符串s从p开始转换成float
doublestod(s)stod(s,p)把字符串s从p开始转换成double
longstol(s)stol(s,p,b)把字符串s从p开始转换成b进制的longstol(s, 0, 10)

三、char[]转num

头文件

#include<cstdio>
char ch[100] = "-456.78";
// 注:atof(ch)只返回double数字,因此需要float可以自行转换成float
double num = atof(ch);   // num = -456.78   
cout << typeid(num == typeid(double) << endl;  // true

下面给出常用的转换方法,完整转换方法请见《C++中的字符串(String)和数值转换》

转换数字的类型默认功能
intatoi(s)将字符串s[n]转换为整型值
doubleatof(s)将字符串s[n]转换为double
longatol(s)将字符串s[n]转换为long

四、char[]与string的相互转换

  • 4.1 字符数组char[]转换string(直接赋值即可)
char ch[100] = "Hellow World";
string str = ch;  // str = "Hellow World"
cout << typeid(str == typeid(string) << endl;  // true
  • 4.2 字符数组string转换char[]
string str = "Hellow World";  
char ch[100] = {0};
for (int i=0;i < str.length();i++)
	ch[i] = str[i];
cout << ch << endl;  // ch = "Hellow World"

五、字符串拼接

5.1 string + string

string str1 = "aaa";
strint str2 = "bbb";
cout << str1 + str2 << endl; // "aaabbb"
cout << str1 + "bbb" << endl; // "aaabbb"

5.1 string + char*

string str1 = "aaa";
char* str2 = "bbb";
cout << str1 + str2 << endl; // "aaabbb"

持续积累中~

参考文献

[1] C++ 字符串与字符数组详解
[2] C++中的字符串(String)和数值转换

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SL_World

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值