Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert char to string in c++

Tags:

c++

string

char

I am trying to reduce a string by giving it to a function. For example, if i have "abrakadabra", the function shall return a string of "abrkd". Which means that all characters should exist only once in the return value.

I have the following function:

string textletters(string text) {
    string ret = "";
    for (unsigned i = 0; i < text.length(); i++) {
        if (i == 0) {
            ret += str;
        } else {
            bool exist = false;
            for (unsigned j = 0; j < i; j++) {
                if (text.at(i) == text.at(j) {
                    exist = true;
                }
            }
            if (!exist) {
                ret += str;
            }
        }
    }
    return ret;
}

I know that text.at(i) gives a char back. But I want to convert this char to a string so I can concatenate it.

like image 842
moody Avatar asked Dec 14 '15 14:12

moody


People also ask

How do I convert a char to a string?

We can convert a char to a string object in java by using the Character. toString() method.

Can I change char to string C++?

2) Using string class operator = The one which we will be using today is: string& operator= (char c); This operator assigns a new character c to the string by replacing its current contents.

Is char * A string in C?

This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.


1 Answers

Use push_back method to append single char to a std::string. You can also use operator += to do that.

like image 51
Andrew Komiagin Avatar answered Sep 18 '22 05:09

Andrew Komiagin