如何在一行上连接多个 C++ 字符串?
-
20-08-2019 - |
题
C# 具有一种语法功能,您可以在一行上将多种数据类型连接在一起。
string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;
C++ 中的等价物是什么?据我所知,您必须在单独的行上完成所有操作,因为它不支持使用 + 运算符的多个字符串/变量。这还可以,但看起来不太整洁。
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
上面的代码会产生错误。
解决方案
#include <sstream>
#include <string>
std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();
看看这个大师从香草萨特本周文章作者:庄园农场的字符串格式化程序
其他提示
在5年内没有提到 .append
?
#include <string>
std::string s;
s.append("Hello world, ");
s.append("nice to see you, ");
s.append("or not.");
s += "Hello world, " + "nice to see you, " + "or not.";
这些字符数组文本不是C ++的std ::串 - 你定义将它们转换:
s += string("Hello world, ") + string("nice to see you, ") + string("or not.");
要转换整数(或任何其它可流型)可以使用升压lexical_cast的,或提供自己的函数:
template <typename T>
string Str( const T & t ) {
ostringstream os;
os << t;
return os.str();
}
您现在可以说这样的话:
string s = "The meaning is " + Str( 42 );
您的代码可以写为 1 ,
s = "Hello world," "nice to see you," "or not."
...但我怀疑这就是你要找的内容。在你的情况,你可能寻找流:
std::stringstream ss;
ss << "Hello world, " << 42 << "nice to see you.";
std::string s = ss.str();
1 “的可以写为强>”:这只适用于字符串文字。级联是由编译器完成的。
使用C ++ 14个用户定义的文字和std::to_string
代码变得更容易。
using namespace std::literals::string_literals;
std::string str;
str += "Hello World, "s + "nice to see you, "s + "or not"s;
str += "Hello World, "s + std::to_string(my_int) + other_string;
请注意级联字符串文字可以在编译时进行。只是删除+
。
str += "Hello World, " "nice to see you, " "or not";
要提供一种解决方案,是更单行肥胖型:函数concat
可被实现为基于溶液减少“经典”的stringstream到的单一语句即可。
它是基于可变参数模板和完美转发。
<强>用法:强>
std::string s = concat(someObject, " Hello, ", 42, " I concatenate", anyStreamableType);
<强>实施强>
void addToStream(std::ostringstream&)
{
}
template<typename T, typename... Args>
void addToStream(std::ostringstream& a_stream, T&& a_value, Args&&... a_args)
{
a_stream << std::forward<T>(a_value);
addToStream(a_stream, std::forward<Args>(a_args)...);
}
template<typename... Args>
std::string concat(Args&&... a_args)
{
std::ostringstream s;
addToStream(s, std::forward<Args>(a_args)...);
return s.str();
}
升压::格式
或std :: stringstream的
std::stringstream msg;
msg << "Hello world, " << myInt << niceToSeeYouString;
msg.str(); // returns std::string object
这 实际问题 是将字符串文字与 +
在 C++ 中失败:
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
上面的代码会产生错误。
在 C++ 中(也在 C 中),您可以通过将字符串文字紧邻放置来连接它们:
string s0 = "Hello world, " "nice to see you, " "or not.";
string s1 = "Hello world, " /*same*/ "nice to see you, " /*result*/ "or not.";
string s2 =
"Hello world, " /*line breaks in source code as well as*/
"nice to see you, " /*comments don't matter*/
"or not.";
如果您在宏中生成代码,这是有道理的:
#define TRACE(arg) cout << #arg ":" << (arg) << endl;
...一个可以像这样使用的简单宏
int a = 5;
TRACE(a)
a += 7;
TRACE(a)
TRACE(a+7)
TRACE(17*11)
(现场演示...)
或者,如果您坚持使用 +
对于字符串文字(正如已经建议的 下划线_d):
string s = string("Hello world, ")+"nice to see you, "+"or not.";
另一种解决方案结合了字符串和 const char*
对于每个串联步骤
string s;
s += "Hello world, "
s += "nice to see you, "
s += "or not.";
auto s = string("one").append("two").append("three")
您必须定义运算符+()每次数据输入你想concenate字符串,但由于运营商<<是为大多数类型的定义,你应该使用std :: stringstream的。
该死,通过50秒击败...
如果你写出来的+=
,它看起来几乎一样C#
string s("Some initial data. "); int i = 5;
s = s + "Hello world, " + "nice to see you, " + to_string(i) + "\n";
正如其他表示,与OP代码的主要问题是,操作者+
不串联const char *
;它的工作原理与std::string
,虽然。
下面是一个使用C ++ 11个lambdas和for_each
和允许提供一个separator
以分离字符串另一种解决方案:
#include <vector>
#include <algorithm>
#include <iterator>
#include <sstream>
string join(const string& separator,
const vector<string>& strings)
{
if (strings.empty())
return "";
if (strings.size() == 1)
return strings[0];
stringstream ss;
ss << strings[0];
auto aggregate = [&ss, &separator](const string& s) { ss << separator << s; };
for_each(begin(strings) + 1, end(strings), aggregate);
return ss.str();
}
用法:
std::vector<std::string> strings { "a", "b", "c" };
std::string joinedStrings = join(", ", strings);
这似乎很好地扩展(线性),至少我的计算机上快速测试之后;这里有一个快速的测试,我已经写了:
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <chrono>
using namespace std;
string join(const string& separator,
const vector<string>& strings)
{
if (strings.empty())
return "";
if (strings.size() == 1)
return strings[0];
stringstream ss;
ss << strings[0];
auto aggregate = [&ss, &separator](const string& s) { ss << separator << s; };
for_each(begin(strings) + 1, end(strings), aggregate);
return ss.str();
}
int main()
{
const int reps = 1000;
const string sep = ", ";
auto generator = [](){return "abcde";};
vector<string> strings10(10);
generate(begin(strings10), end(strings10), generator);
vector<string> strings100(100);
generate(begin(strings100), end(strings100), generator);
vector<string> strings1000(1000);
generate(begin(strings1000), end(strings1000), generator);
vector<string> strings10000(10000);
generate(begin(strings10000), end(strings10000), generator);
auto t1 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings10);
}
auto t2 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings100);
}
auto t3 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings1000);
}
auto t4 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings10000);
}
auto t5 = chrono::system_clock::now();
auto d1 = chrono::duration_cast<chrono::milliseconds>(t2 - t1);
auto d2 = chrono::duration_cast<chrono::milliseconds>(t3 - t2);
auto d3 = chrono::duration_cast<chrono::milliseconds>(t4 - t3);
auto d4 = chrono::duration_cast<chrono::milliseconds>(t5 - t4);
cout << "join(10) : " << d1.count() << endl;
cout << "join(100) : " << d2.count() << endl;
cout << "join(1000) : " << d3.count() << endl;
cout << "join(10000): " << d4.count() << endl;
}
结果(毫秒):
join(10) : 2
join(100) : 10
join(1000) : 91
join(10000): 898
也许你喜欢我的“流光”的解决方案,真正做到在一个行:
#include <iostream>
#include <sstream>
using namespace std;
class Streamer // class for one line string generation
{
public:
Streamer& clear() // clear content
{
ss.str(""); // set to empty string
ss.clear(); // clear error flags
return *this;
}
template <typename T>
friend Streamer& operator<<(Streamer& streamer,T str); // add to streamer
string str() // get current string
{ return ss.str();}
private:
stringstream ss;
};
template <typename T>
Streamer& operator<<(Streamer& streamer,T str)
{ streamer.ss<<str;return streamer;}
Streamer streamer; // make this a global variable
class MyTestClass // just a test class
{
public:
MyTestClass() : data(0.12345){}
friend ostream& operator<<(ostream& os,const MyTestClass& myClass);
private:
double data;
};
ostream& operator<<(ostream& os,const MyTestClass& myClass) // print test class
{ return os<<myClass.data;}
int main()
{
int i=0;
string s1=(streamer.clear()<<"foo"<<"bar"<<"test").str(); // test strings
string s2=(streamer.clear()<<"i:"<<i++<<" "<<i++<<" "<<i++<<" "<<0.666).str(); // test numbers
string s3=(streamer.clear()<<"test class:"<<MyTestClass()).str(); // test with test class
cout<<"s1: '"<<s1<<"'"<<endl;
cout<<"s2: '"<<s2<<"'"<<endl;
cout<<"s3: '"<<s3<<"'"<<endl;
}
您可以使用该标头这方面: https://github.com/theypsilon/concat
using namespace concat;
assert(concat(1,2,3,4,5) == "12345");
引擎盖下要使用一个std :: ostringstream。
如果您愿意使用c++11
可以利用用户定义字符串文字一>并定义超负荷加操作者要std::string
对象和任何其它物体的两个函数的模板。唯一的缺陷是不超载std::string
的加运营,否则编译器不知道要使用哪个运营商。您可以通过使用模板做到这一点 std::enable_if
从的: //en.cppreference.com/w/cpp/header/type_traits”相对= “nofollow”> type_traits
。该字符串之后的表现就像在Java或C#。见我的详细信息,例如执行。
主代码
#include <iostream>
#include "c_sharp_strings.hpp"
using namespace std;
int main()
{
int i = 0;
float f = 0.4;
double d = 1.3e-2;
string s;
s += "Hello world, "_ + "nice to see you. "_ + i
+ " "_ + 47 + " "_ + f + ',' + d;
cout << s << endl;
return 0;
}
文件c_sharp_strings.hpp
包含在你想拥有这些字符串的所有所有的地方这个头文件。
#ifndef C_SHARP_STRING_H_INCLUDED
#define C_SHARP_STRING_H_INCLUDED
#include <type_traits>
#include <string>
inline std::string operator "" _(const char a[], long unsigned int i)
{
return std::string(a);
}
template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
!std::is_same<char, T>::value &&
!std::is_same<const char*, T>::value, std::string>::type
operator+ (std::string s, T i)
{
return s + std::to_string(i);
}
template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
!std::is_same<char, T>::value &&
!std::is_same<const char*, T>::value, std::string>::type
operator+ (T i, std::string s)
{
return std::to_string(i) + s;
}
#endif // C_SHARP_STRING_H_INCLUDED
您也可以 “扩展” string类,并选择你喜欢的运算符(<<,&,|,等...)
下面是使用代码的operator <<显示存在与流没有冲突
请注意:如果取消注释s1.reserve(30),仅存在3个新的()的操作员请求(1将s1,1为S2,1为储备;不能在构造时间不幸保留);毫无保留地,S1具有与它长到请求更多的存储器,所以它取决于你的编译器实现生长因子(矿似乎是1.5,5个新的()调用在本实施例中)
namespace perso {
class string:public std::string {
public:
string(): std::string(){}
template<typename T>
string(const T v): std::string(v) {}
template<typename T>
string& operator<<(const T s){
*this+=s;
return *this;
}
};
}
using namespace std;
int main()
{
using string = perso::string;
string s1, s2="she";
//s1.reserve(30);
s1 << "no " << "sunshine when " << s2 << '\'' << 's' << " gone";
cout << "Aint't "<< s1 << " ..." << endl;
return 0;
}
这样的事情对我的作品
namespace detail {
void concat_impl(std::ostream&) { /* do nothing */ }
template<typename T, typename ...Args>
void concat_impl(std::ostream& os, const T& t, Args&&... args)
{
os << t;
concat_impl(os, std::forward<Args>(args)...);
}
} /* namespace detail */
template<typename ...Args>
std::string concat(Args&&... args)
{
std::ostringstream os;
detail::concat_impl(os, std::forward<Args>(args)...);
return os.str();
}
// ...
std::string s{"Hello World, "};
s = concat(s, myInt, niceToSeeYouString, myChar, myFoo);
我做了一个类var_string为我的项目,使生活更轻松。例子:
var_string x("abc %d %s", 123, "def");
std::string y = (std::string)x;
const char *z = x.c_str();
类本身:
#include <stdlib.h>
#include <stdarg.h>
class var_string
{
public:
var_string(const char *cmd, ...)
{
va_list args;
va_start(args, cmd);
vsnprintf(buffer, sizeof(buffer) - 1, cmd, args);
}
~var_string() {}
operator std::string()
{
return std::string(buffer);
}
operator char*()
{
return buffer;
}
const char *c_str()
{
return buffer;
}
int system()
{
return ::system(buffer);
}
private:
char buffer[4096];
};
还是想知道是否会出现在C ++更好的东西?
在C11:
void printMessage(std::string&& message) {
std::cout << message << std::endl;
return message;
}
这允许您创建函数调用是这样的:
printMessage("message number : " + std::to_string(id));
将打印:消息号:10
下面是一衬垫溶液:
#include <iostream>
#include <string>
int main() {
std::string s = std::string("Hi") + " there" + " friends";
std::cout << s << std::endl;
std::string r = std::string("Magic number: ") + std::to_string(13) + "!";
std::cout << r << std::endl;
return 0;
}
虽然这是一个很小的有点难看,我觉得这是关于清洁的C作为你的猫得到++。
我们是铸造的第一个参数的std::string
,然后使用(左到右)的operator+
评价顺序,以确保其的左强>操作数总是一个std::string
。以这种方式,我们串接在左侧与右侧的std::string
操作数const char *
和返回另一个std::string
,级联的效果。
注意:存在用于右操作数几个选项,包括const char *
,std::string
,和char
这是由你来决定一个神奇的数字是13或6227020800。
字符串流用的λ函数的简单preproccessor宏似乎很好:
#include <sstream>
#define make_string(args) []{std::stringstream ss; ss << args; return ss;}()
和然后
auto str = make_string("hello" << " there" << 10 << '$');
这对我的作品:
#include <iostream>
using namespace std;
#define CONCAT2(a,b) string(a)+string(b)
#define CONCAT3(a,b,c) string(a)+string(b)+string(c)
#define CONCAT4(a,b,c,d) string(a)+string(b)+string(c)+string(d)
#define HOMEDIR "c:\\example"
int main()
{
const char* filename = "myfile";
string path = CONCAT4(HOMEDIR,"\\",filename,".txt");
cout << path;
return 0;
}
输出:
c:\example\myfile.txt
你试过避免+ =? 而是使用VAR = VAR + ... 它为我工作。
#include <iostream.h> // for string
string myName = "";
int _age = 30;
myName = myName + "Vincent" + "Thorpe" + 30 + " " + 2019;