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

一、摘要

在算法竞赛题目和平时的编程中经常会遇到处理字符串的问题,常用的方法是使用string类处理字符串。但是在一些C语言版本的函数中智能处理char类型的字符串,因此掌握string与char类型数据转换会提供很大的便利。本文第二部分简要介绍了C++中stringchar*char[]之间的转换代码,另外还介绍了char字符类型与前三者的转换代码。

二、string、char*和char[] 之间的转换

1. string 转为 char*

#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main(int, char**) {
    string str = "Hello World";
    char* s1 = nullptr;
    char* s2 = nullptr;
    const char* s3;
    s1 = new char[str.length() + 1];
    s2 = new char[str.length() + 1];
    strcpy(s1, str.c_str());
    strcpy(s2, str.data());
    s3 = str.c_str();
    cout << s1 << endl;
    cout << s2 << endl;
    cout << s3 << endl;
    return 0;
}

输出结果:

Hello World
Hello World
Hello World

需要注意的是:

  • s3const char*类型,因此无法通过类似s3[0]='x'的代码修改原始的str
  • 如果想要通过char* s4达到修改原始str的效果,可以如下代码达到该目的:
char* s4 = &str[0];
s4[0] = 'x';
  • str.c_str()str.data()函数功能完全相同,都是返回一个const char*

2. char* 转为 string

代码:

#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main(int, char**) {
    char* s = "Hello World";
    string str1 = s;
    string str2(s);
    string str3 = string(s);
    cout << str1 << endl;
    cout << str2 << endl;
    cout << str3 << endl;
    return 0;
}

输出:

Hello World
Hello World
Hello World

3. string 转为char[]

在将string str转为char s[]时需要保证s[]的空间大小大于str的大小+1,因为在s[]中在字符串在最后需要使用\0作为字符串的结束符号。
代码:

#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main(int, char**) {
    string str = "Hello World";
    char s1[str.length() + 1];
    char s2[str.length() + 1];
    strcpy(s1, str.c_str());
    strcpy(s2, str.data());
    cout << s1 << endl;
    cout << s2 << endl;
    return 0;
}

输出结果:

Hello World
Hello World

4. char[]转为string

char s1[]char* s2类似,因为在C语言的数组中,数组名称即为数组的首地址,而地址又可以使用指针表示,因此可以认为char s1[]cahr* s2等价。
代码:

#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main(int, char**) {
    char s[12] = "Hello World";
    string str1 = s;
    string str2(s);
    string str3 = string(s);
    cout << str1 << endl;
    cout << str2 << endl;
    cout << str3 << endl;
    return 0;
}

输出结果:

Hello World
Hello World
Hello World

三、参考

[1]. C++中string、char *、char[]的转换

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值