String和char之间的转换

1.string转const char*

	string str = "abc";
	const char *pa = str.data();//data()函数不会添加'\0'结束符
	cout << pa << endl;
	const char *p = str.c_str();//c_str()会在数据的末尾添加'\0'结束符,多数用于使用字符串场合。
	cout << p << endl;

        但是,上面这种用法很不安全,因为p最后指向的内容是垃圾值,str对象被析构了。而且c_str()返回的是一个临时指针,不能对其进行操作。

2.string转char*

	string s = "abcd";
	char *ch;
	ch = (char*)malloc((s.length()) * sizeof(char));
	s.copy(ch, s.length(),0);//把当前串中以0开始的s.length()个字符拷贝到以ch为起始位置的字符数组中,返回实际拷贝的数目
	cout << ch;

3.string转char[]

1)strcpy_s
#include <iostream>
using namespace std;
#include <string>

int main()
{
	char ch[5];
	string s = "abcd";
	strcpy_s(ch, s.c_str());
	cout << ch << endl;

	return 0;
}
2)遍历添加
#include <iostream>
using namespace std;
#include <string>

int main()
{
	string pp = "helloworld";
	char p[20];
	int i;
	for (i = 0; i < pp.length(); i++)
	{
		p[i] = pp[i];
	}
	p[i] = '\0';  //添加结束符

	cout << p << endl;

	return 0;
}

4.const char *或者const char []或者char []转string

#include <iostream>
using namespace std;
#include <string>

int main()
{
	string a;
	const char* b = "study";
	const char c[] = "study well";
    char p[20] = "helloworld";

	a = b;
	cout << a << endl;
	cout << a.length() << endl;

	a = c;
	cout << a << endl;
	cout << a.length() << endl;

	a = p;
    cout << a << endl;
	cout << a.length() << endl;

	return 0;
}

5.char[]转char*或者const char[]转const char*

#include <iostream>
using namespace std;
#include <string>

int main()
{
	char a[20] = "hello world";
	char* p = a;
	cout << p << endl;

	const char a1[20] = "hello world";
	const char* p1 = a1;

	cout << p1 << endl;


	return 0;
}

6.const char*转char[]

1)strcpy_s
#include <iostream>
using namespace std;
#include <string>

int main()
{
	char arr[20];
	const char* tmp = "helloworld";
	strcpy_s(arr, tmp);

	cout << arr << endl;

	return 0;
}
2)循环遍历
#include <iostream>
using namespace std;
#include <string>

int main()
{
	char arr[20];
	const char* tmp = "hello world";
	int i = 0;
	while (*tmp != '\0')
	{
		arr[i++] = *tmp++;
	}
	arr[i] = '\0';  //添加结束符

	cout << arr << endl;

	return 0;
}

7.char*转string

#include <iostream>
using namespace std;
#include <string>

int main()
{
	char a[10] = "hello";
	char *b = a;
	string c = b;

	cout << a << endl;
	cout << b << endl;
	cout << c << endl;

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值