简体   繁体   中英

Concatenate plain char and string?

im getting totally confused by this seemingly simple problem.

I have a pain old char, and I want to concatenate it in the middle of a string. Like so.

string missingOptionArg(char missingArg) {
     return "Option -" + missingArg + " requires an operand";
}

I was guessing the + operand was smart enough to deal with this sort of trivial thing, if not, what would be the simplest way of doing this?

To concatenate string literal and char:

std::string miString = std::string("something") + c;

A similar thing happens when you need to concat two strings literals.

Note that "something" is not a std::string , it is a pointer to an array of chars. Then you can't concatenate two string literals using +, that would be adding two pointers and is not what you want.

The correction of your code is in Igor's comment.

Accepted answer is the simplest but other ways to achieve the concatenation.

#include <iostream>
#include <string>

using namespace std;

string missingOptionArgRet(char missingArg) {

     string s("Option -");
     s += missingArg;
     s += " requires an operand";
     return s;
}

void missingOptionArgOut(char missingArg, std::string* out) {

     *out = "Option -";
     *out += missingArg;
     *out += " requires an operand";
}

main(int, char**)
{
    string s1 = missingOptionArgRet('x');
    string s2;

    missingOptionArgOut('x', &s2);

    cout << "s1 = " << s1 << '\n';
    cout << "s2 = " << s2 << '\n';
}

Using += rather than + will prevent temporary string objects. Also there are 2 options. Return by value missingOptionArgRet . This has disadvantage that as a result of return by value the string must be copied to the caller.

The second option missingOptionArgOut can prevent this at the cost of slightly more verbose code. I pass in an already constructed string (by pointer to make it clear its a variable to be modified, but could be passed by reference).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM