C++ 字符串转换

版权声明:转载请注明出处。作者:两仪织,博客地址:http://blog.csdn.net/u013894427 https://blog.csdn.net/u013894427/article/details/83782194

头文件

#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(); 

猜你喜欢

转载自blog.csdn.net/u013894427/article/details/83782194
今日推荐