Home > Backend Development > C#.Net Tutorial > How to convert char array to string

How to convert char array to string

王林
Release: 2020-10-22 11:32:43
Original
26289 people have browsed it

char数组转string的方法:可以通过直接赋值的方法来实现,如【char a[]=" abc  d\0efg ";string s=a;】。如果要实现string转char数组,可以调用strcpy函数和data函数。

How to convert char array to string

一、char数组转string:

1、可以直接赋值

(推荐教程:c语言教程

2、代码:

#include<iostream>
using namespace std;
 
int main()
{
	char a[]=" abc  d\0efg "; 	
	
	string s=a;  //直接赋值
	
	cout<<s;	
	return 0;
	
}
Copy after login

结果:

How to convert char array to string

二、string转char数组:

1、调用strcpy函数,和字符串的data函数: (char数组可以更改)(string转char数组)

(1)strcpy不能赋值给char指针 ,只能赋值给char数组;

(2)char数组长度,必须大于等于string长度。

代码:

#include<iostream>
#include<cstring>
using namespace std;
 
int main()
{	
	string s="123456"; 
	char c[s.length()]; 
	
	/*
	**调用strcpy函数,和字符串的data函数 
	**1、strcpy不能赋值给char指针 ,只能赋值给char数组 
	**2、char数组长度,必须大于等于string长度 
	*/ 
	strcpy(c,s.data()); 	
	
	c[0]=&#39;6&#39;;
	
	cout<<c<<endl;
	cout<<strlen(c);
	
	return 0;
	
}
Copy after login

结果:

How to convert char array to string

The above is the detailed content of How to convert char array to string. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template