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
Release: 2024-11-04 00:48:30
Original
972 people have browsed it

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>
Copy after login

Output:

"
"
"
Copy after login

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!

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