C++ 字符串转换

头文件

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

c_str函数

C++标准库中的函数,作用是把字符串转变为字符数组以兼容C语言(C语言中没有string类型)

atoi()

C/C++标准库中的函数,作用是把字符串转换为数字,里面传递的是C里面字符数组,因此,如果是C++字符串,需要用c_str()函数进行转换

类似的还有atof(),atol()

itoa()

C/C++标准库中的函数,作用是把整形值转变为字符串(C语言中的)。
类似的还有:ltoa(),ultoa()

char数组转字符串

方法:直接赋值

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

using namespace std;

int main(){
	const char *x="hello x";
	const char y[]="hello y";
	string z;
	z=x;
	printf("z=%s\n",z.c_str());
	z=y;
	printf("z=%s\n",z.c_str());
	
	return 0;
}

结果为

z=hello x
z=hello y

字符串转为char数组

方法:使用strcpy函数

char c[20]; 
string s="1234"; 
strcpy(c,s.c_str()); 

char指针转字符串

方法:直接赋值

const char* c_s ="abc";
string s(c_s);

const char*或者char*都可以

char* c_s ="abc";
string s(c_s);

字符串转为char指针

方法一:使用string.data函数

string str="abc"; 
char *p=str.data(); 

方法二:使用string.c_str函数

string str="gdfd"; 
char *p=str.c_str(); 
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值