c++中如何添加多个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2300895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:57:14  来源:igfitidea点击:

How to add many strings in c++

c++stringaddconcat

提问by cpx

As I know that C++ only allows to add 2 strings together, i.e: s = s1 + s2

据我所知,C++ 只允许将 2 个字符串相加,即: s = s1 + s2

But how can I add many strings together? Like:

但是如何将多个字符串相加呢?喜欢:

s = s1 + s2 + s3 + s4 + ... + sn

回答by cpx

If you're trying to append string objects of std::string class, this should work.

如果您尝试附加 std::string 类的字符串对象,这应该可行。

string s1 = "string1";
string s2 = "string2";
string s3 = "string3";

string s = s1 + s2 + s3;

OR

或者

string s = string("s1") + string("s2") + string("s3") ...

回答by Billy ONeal

First of all, you can do the +sn thing just fine. Though it's going to take exponentialquadradic(see comments) time assuming you're using std::basic_string<t>strings on C++03.

首先,你可以很好地做 +sn 的事情。尽管假设您在 C++03 上使用字符串,它将花费指数二次(见评论)时间std::basic_string<t>

You can use the std::basic_string<t>::appendin concert with std::basic_string<t>::reserveto concatenate your string in O(n) time.

您可以使用std::basic_string<t>::appendin concert withstd::basic_string<t>::reserve在 O(n) 时间内连接您的字符串。

EDIT: For example

编辑:例如

string a;
//either
a.append(s1).append(s2).append(s3);
//or
a.append("I'm a string!").append("I am another string!");

回答by R Samuel Klatchko

s = s1 + s2 + s3 + .. + sn;

will work although it could create a lot of temporaries (a good optimizing compiler should help) because it will effectively be interpreted as:

尽管它可能会创建很多临时文件(一个好的优化编译器应该会有所帮助),但它会起作用,因为它会被有效地解释为:

string tmp1 = s1 + s2;
string tmp2 = tmp1 + s3;
string tmp3 = tmp2 + s4;
...
s = tmpn + sn;

An alternate way that is guaranteed not to create temporaries is:

保证不创建临时文件的另一种方法是:

s = s1;
s += s2;
s += s3;
...
s += sn;

回答by Nikolai Fetissov

std::ostringstreamis build for that, see example here. It's easy:

std::ostringstream是为此而构建的,请参见此处的示例。这很简单:

std::ostringstream out;
out << "a" << "b" << "c" << .... << "z";
std::string str( out.str());

回答by QuentinUK

Use a template to add strings, char* and char's to form a string

使用模板添加字符串,char* 和char's 组成一个字符串

strlen:-

斯特伦:-

#include <iostream>
#include <cstring>

// it_pair to wrap a pair of iterators for a for(:) loop
template<typename IT> 
class it_pair
    {
    IT b;
    IT e;
public:
    auto begin() const
        {
        return b;
        }
    auto end() const
        {
        return e;
        }
    };

// string length
template<typename S> auto strlen(const S& s) -> decltype(s.size())
    {
    return s.size();
    }

auto strlen(char c) -> size_t
    {
    return 1u;
    }

auto strlen(const std::initializer_list<char>& il) -> size_t
    {
    return il.size();
    }

template<typename IT>
auto strlen(const it_pair<IT>& p)
    {
    auto len = size_t{};
    for(const auto& s:p)
        len += strlen(s);
    return len;
    }

template<typename S, typename ...SS> auto strlen(S s, SS&... ss) -> size_t
    {
    return strlen(s) + strlen(ss...);
    }

appending strings

附加字符串

// terminate recursion
template<typename TA, typename TB>
void append(TA& a, TB& b)
    {
    a.append(b);
    }

// special case for a character
template<>
void append<std::string, const char>(std::string& a, const char& b)
    {
    a.append(1, b);
    }

// special case for a collection of strings
template<typename TA, typename TB>
void append(TA& a, const it_pair<TB>& p)
    {
    for(const auto& x: p)
        a.append(x);
    }

// recursion append
template<typename TA, typename TB, typename ...TT>
void append(TA& a, TB& b, TT&... tt)
    {
    append(a, b);
    append(a, tt...);
    }

template<typename ...TT>
std::string string_add(const TT& ... tt)
    {
    std::string s;
    s.reserve(strlen(tt...));
    append(s, tt...);
    return s;
    }

template<typename IT>
auto make_it_pair(IT b, IT e)
    {
    return it_pair<IT>{b, e};
    }

template<typename T>
auto make_it_pair(const T& t)
    {
    using namespace std;
    return make_it_pair(cbegin(t), cend(t));
    }

main example

主要例子

int main()
    {
    const char * s[] = {"vw", "xyz"};
    std::vector<std::string> v{"l", "mn", "opqr"};
    std::string a("a");
    std::string b("bc");
    std::string c("def");
    std::cout << string_add(a, b+c, "ghij", make_it_pair(v), 'k', make_it_pair(s));
    }

回答by Michael Hall

If you want to be able to do this

如果你想能够做到这一点

  • Efficiently, i.e without incurring quadratic time
  • Without overwriting the original variable
  • Without creating temporary variables
  • 高效,即不产生二次时间
  • 不覆盖原始变量
  • 不创建临时变量

Then this will do the job

然后这将完成工作

auto s = std::string(s1).append(s2).append(s3).append(sn);  

And if you like things nicely formatted

如果你喜欢格式很好的东西

auto s = std::string(s1).append(s2)
                        .append(s3)
                        .append(sn)