字符串,字符数组,数字相互转化

一.字符数组转字符串

#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;
} 
  • 5
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值