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
Release: 2024-11-03 18:50:30
Original
513 people have browsed it

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template