10 ways to convert a char to a string in C++

In this post, we will discuss various methods to convert a char to a string in C++.


 

1. std::string constructor

Simple solution would be to use string class fill constructor string (size_t n, char c); which fills the string with n copies of character c.

 

Download   Run Code

 

2. Using std::stringstream

Another good alternative is to use string stream to convert between strings and other numerical types. The idea is to insert the given character into a stream and then write contents of its buffer to the std::string.

 

Download   Run Code

 

3. std::string::push_back

Another commonly used solution is to use push_back() function which is overloaded for chars and appends a character to the end of the string.

 

Download   Run Code

 

4. std::string::operator+=

string& operator+= (char c);

The string +=operator is overloaded for chars. We can use it to append character at the end the string as shown below:

 

Download   Run Code

 

5. std::string::operator=

string& operator= (char c);

Similar to the +=operator, the =operator is also overloaded for chars. We can use it to replace the contents of a string with a single char.

 

Download   Run Code

 

6. std::string::append

string& append (size_t n, char c);

We can also use append() function to append n copies of character c as demonstrated below:

 

Download   Run Code

 

7. std::string::assign

string& assign (size_t n, char c);

The assign() function replaces the current value of the string with n copies of character c. We can use it as shown below:

 

Download   Run Code

 

8. std::string::insert

string& insert (size_t pos, size_t n, char c);

We can use insert() that inserts n copies of character c beginning at character pos.

 

Download   Run Code

 

9. std::string::replace

string& replace (size_t pos, size_t len, size_t n, char c);

The replace() function replaces the portion of the string (len characters beginning at character pos) by n copies of character c. We can use it as shown below:

 

Download   Run Code

 

10. Converting char to c-string

Finally, we can also convert the char to a c-string and then convert the c-string to a std::string using the fill constructor or std::string::append or std::string::assign.

 

Download   Run Code

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Categories

Leave a Reply

Notify of
avatar
wpDiscuz