字符串相连

阅读量: 213 编辑

字符串连接就是将多个字符串拼接成一个字符串。

一、使用+连接

字符串的连接常用+完成。

代码案例

string a = "hello";
string b = "world";

string c = a + b; //多个字符串可以使用多个 + 连接
cout << c << endl;

只能进行字符串直接连接,不可以和数字等类型进行连接。

string a = "hello";
string b = a + 100; //错误  hello100

可以先把整数转为字符串,再相连。

二、数字和字符串转换

数字转成字符,字符串转成数字,使用<sstream>头文件。

#include <iostream>

//使用这个头文件转换
#include <sstream>

using namespace std;

int main() {
    
    //数字转字符串 
    float a = 123.456;
    
    stringstream sstream;
	sstream << a; //a放到sstream中 
	
	string a_str = sstream.str();//用sstream转换 
	cout << a_str << endl;
	
    //清空stringstream,改变读写位置
    sstream.str("");
    sstream.clear();
	
	//字符串转数字 
	string b = "123.456";
	sstream << b; //b放到sstream中 
	
	float f;
    sstream >> f; //将sstream转换成 float 
	cout << f << endl;
		
	return 0;
}

相当于用 stringstream 作为一个“中间人”进行转换。

爱码岛编程公众号
试卷资料
爱码岛编程小程序
在线刷题
苏ICP备13052010号
©2023 南京匠成信息科技有限公司