一.字符数组转字符串
#include<iostream>
#include<string>
using namespace std;
int main(){
char str[5]={'a','b','c','d'};
string s1(str);//声明时赋值转化
cout<<s1<<endl;
string s2;
s2=str;//直接赋值转化
cout<<s2<<endl;
return 0;
}
二.字符串转化为字符数组
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
int main(){
string s="abcd";
char str1[5];
strcpy(str1,s.c_str());//复制到字符数组
printf("%s\n",str1);
char str2[5];
sprintf(str2,"%s",s.c_str());//利用函数转化
printf("%s",str2);
return 0;
}
拓展:
const char *c_str();
c_str()函数返回一个指向正规C字符串的指针,内容与本string串相同
这是为了和C语言兼容,在C语言中没有string类型,故必须同过string类对象的成员函数c_str()对象转化成C中的字符串样式
三.字符串字符数组转化为数字
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
int main(){
//字符串转化为数字
string s="1234";
int number1=atoi(s.c_str());
cout<<number1<<endl;
//字符数组转化为数字
char str[5]={'5','6','7','8'};
int number2=atoi(str);
cout<<number2<<endl;
return 0;
}
拓展:
C 库函数 int atoi(const char *str) 把参数 str 所指向的字符串转换为一个整数(类型为 int 型)
函数原型:int atoi(const char *str);
头文件:#include <stdlib.h>
跳过前面的空格字符,直到遇上数字或正负号才开始做转换,而再遇到非数字或字符串时(’\0’)才结束转化,并将结果返回(返回转换后的整型数)。
函数名 | 作 用 |
---|---|
atoi() | 将字符串转化为整型 |
atof() | 将字符串转换为双精度浮点型值 |
atol() | 将字符串转换为长整型值 |
strtod() | 将字符串转换为双精度浮点型值,并报告不能被转换的所有剩余数字 |
strtol() | 将字符串转换为长整值,并报告不能被转换的所有剩余数字 |
strtoul() | 将字符串转换为无符号长整型值,并报告不能被转换的所有剩余数字 |
四.数字转化为字符数组或字符串
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main(){
//数字转化为字符数组
int n=100;
char str[10];
sprintf(str,"%d",n);
printf("%s\n",str);
// 数字转化为字符串
int m=200;
char tt[10];
sprintf(tt,"%d",m);
string s(tt);
cout<<s<<endl;
return 0;
}