Home>Article> How to convert char array to string

How to convert char array to string

DDD
DDD Original
2023-06-09 10:04:42 23961browse

char数组转string的方法:可以通过赋值来实现,使用{char a[]=" abc d\0efg ";string s=a;}语法,让char数组对string直接赋值,执行代码即可完成转换。

How to convert char array to string

本文的操作环境:Windows10系统、C++ 20版本、dell g3电脑。

char数组转string方法:

1、可以直接赋值

2、代码:

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

结果:

How to convert char array to string

拓展:

string转char数组:

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

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

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

代码:

#include #include 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]='6'; cout<
      

结果:

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!

Statement:
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