Home >Backend Development >C++ >How to Convert a Single Character to a `std::string` in C ?

How to Convert a Single Character to a `std::string` in C ?

DDD
DDDOriginal
2024-11-04 00:48:30957browse

How to Convert a Single Character to a `std::string` in C  ?

Creating a std::string from a Single Character

You have a single char value and aim to convert it into a std::string. This process involves transforming the character into a string variable.

To achieve this, you can employ various methods:

  1. std::string Constructor with Length Parameter:

    • std::string s(1, c);
    • This technique specifies the length of the string as 1 and initializes it with the provided character.
  2. std::string with Brace-Enclosed Initializer:

    • std::string s{c};
    • Utilizing a brace-enclosed initializer list, you can directly set the string's value.
  3. push_back() Method:

    • std::string s; s.push_back(c);
    • This method appends the character to an empty string, creating a string with that single character.

Example:

<code class="cpp">char c = 34;

std::string s1(1, c);
std::string s2{c};
std::string s3;
s3.push_back(c);

std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
std::cout << s3 << std::endl;</code>

Output:

"
"
"

The above is the detailed content of How to Convert a Single Character to a `std::string` in C ?. 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