Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a char to a std::string?

Tags:

c++

string

People also ask

Can you concatenate a char to a string in C++?

C++ has a built-in method to concatenate strings. The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function.

How do you add something to a string in C++?

Syntax: string new_string = string init + string add; This is the most easiest method for concatenation of two string. The + operator simply adds the two string and returns a concatenated string.

Can you add two chars to make a string?

You can concatenate chars to a std::string , you just need one of the operands to be a std::string , otherwise you are adding integers.


y += d;

I would use += operator instead of named functions.


Use push_back():

std::string y("Hello worl");
y.push_back('d')
std::cout << y;

To add a char to a std::string var using the append method, you need to use this overload:

std::string::append(size_type _Count, char _Ch)

Edit : Your're right I misunderstood the size_type parameter, displayed in the context help. This is the number of chars to add. So the correct call is

s.append(1, d);

not

s.append(sizeof(char), d);

Or the simpliest way :

s += d;

In addition to the others mentioned, one of the string constructors take a char and the number of repetitions for that char. So you can use that to append a single char.

std::string s = "hell";
s += std::string(1, 'o');

I test the several propositions by running them into a large loop. I used microsoft visual studio 2015 as compiler and my processor is an i7, 8Hz, 2GHz.

    long start = clock();
    int a = 0;
    //100000000
    std::string ret;
    for (int i = 0; i < 60000000; i++)
    {
        ret.append(1, ' ');
        //ret += ' ';
        //ret.push_back(' ');
        //ret.insert(ret.end(), 1, ' ');
        //ret.resize(ret.size() + 1, ' ');
    }
    long stop = clock();
    long test = stop - start;
    return 0;

According to this test, results are :

     operation             time(ms)            note
------------------------------------------------------------------------
append                     66015
+=                         67328      1.02 time slower than 'append'
resize                     83867      1.27 time slower than 'append'
push_back & insert         90000      more than 1.36 time slower than 'append'

Conclusion

+= seems more understandable, but if you mind about speed, use append


Try the += operator link text, append() method link text, or push_back() method link text

The links in this post also contain examples of how to use the respective APIs.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!