search
HomeCommon ProblemHow to convert char array to string

How to convert char array to string

Jun 09, 2023 am 10:04 AM
c languagestringchar type

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<iostream>
using namespace std;
 
int main()
{
char a[]=" abc  d\0efg ";
string s=a;  //直接赋值
cout<<s;
return 0;
}

结果:

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;
}

结果:

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.