C++ 字符串轉換

頭文件

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

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數組

方法一:使用string.data函數

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

方法二:使用string.c_str函數

string str="gdfd"; 
char *p=str.c_str(); 

方法三:使用strcpy函數

char c[20]; 
string s="1234"; 
strcpy(c,s.c_str()); 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章