Home >Backend Development >C++ >How Can I Create a String from a Single Character in C ?

How Can I Create a String from a Single Character in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 18:50:30514browse

How Can I Create a String from a Single Character in C  ?

Creating a String from a Single Character in C

In C , it is possible to create a string from a single character. Here are several methods to achieve this:

  • std::string(n, c): This constructor takes two arguments, where n is the number of characters to create and c is the desired character. For example:
<code class="cpp">char c = 34;
std::string s(1, c);

std::cout << s << std::endl; // Outputs: "</code>
  • std::string{c}: The C 11 initialization syntax can be used to initialize a string with the desired character.
<code class="cpp">char c = 34;
std::string s{c};

std::cout << s << std::endl; // Outputs: "</code>
  • std::string::push_back(c): The push_back() method appends a single character to the string.
<code class="cpp">char c = 34;
std::string s;
s.push_back(c);

std::cout << s << std::endl; // Outputs: "</code>

The above is the detailed content of How Can I Create a String from a Single Character 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