C++中string、char[]、char*之间的转换

目录

1、char[]、char*转string

2、string转char*、char[]


1、char[]、char*转string

char[]、插入*转string比较简单,直接赋值即可进行转换 

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str;
    char x[] = "hello";
    char *y = "Hello";
    str = x;
    cout << "x的值为:" << str << endl;
    str = y;
    cout << "y的值为:" << str << endl;
    return 0;
}

运行结果


2、string转char*、char[]

string转char*有三种方法:

  1. data();
  2. c_str();
  3. copy();

(1)c_str方法

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str;
    str="hello world";

    const char *y = str.c_str();  //这里一定定义为const char *格式,char * p = (char*)str.data()
    cout << "str的值为:" << y << endl;
    
    return 0;
}

运行结果


(2)data方法

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str;
    str="hello world";

    const char *y = str.data();  //这里一定定义为const char *格式,char * p = (char*)str.data()
    
    cout << "str的值为:" << y << endl;
    
    return 0;
}

运行结果


 (3)copy方法

#pragma warning(disable:4996)
#include<iostream>
#include<string>
using namespace std;

int main()
{
    string str;
    str="world";

    char y[20];
    str.copy(y, 5, 0);//第二个参数代表复制的个数,第三个代表复制的位置
    *(y + 5) = '\0';
    
    cout << "str前5个元素的值值为:" << y << endl;
    
    return 0;
}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值