乐闻世界logo
搜索文章和话题

How to convert a char array to a string?

1个答案

1

In C++, a common approach to convert a char array to a string is by utilizing the standard string class (std::string). Here is a specific example demonstrating how to achieve this:

Suppose we have a char array defined as follows:

cpp
char charArray[] = "Hello, World!";

To convert this char array into a std::string object, you can directly employ the constructor of the std::string class, as shown below:

cpp
std::string str(charArray);

This line of code creates a std::string object named str, whose content is copied from charArray.

Additionally, if you need to specify a particular portion of the string for conversion, you can use another constructor that allows you to define the start position and length:

cpp
std::string strPartial(charArray, 7, 5); // Starting from the 7th character of charArray, copying 5 characters

This line of code generates a std::string object containing the content "World".

Thus, you can flexibly convert a char array to a std::string object as needed, and leverage various functionalities and operations provided by std::string.

2024年6月29日 12:07 回复

你的答案