我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
当前回答
作为一个与Qt相关的问题,下面是如何使用Qt:
QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);
字符串变量现在有someIntVariable的值代替%1,someOtherIntVariable的值在结尾。
其他回答
这个问题可以用许多方法解决。我将以两种方式展示它:
Convert the number to string using to_string(i). Using string streams. Code: #include <string> #include <sstream> #include <bits/stdc++.h> #include <iostream> using namespace std; int main() { string name = "John"; int age = 21; string answer1 = ""; // Method 1). string s1 = to_string(age). string s1=to_string(age); // Know the integer get converted into string // where as we know that concatenation can easily be done using '+' in C++ answer1 = name + s1; cout << answer1 << endl; // Method 2). Using string streams ostringstream s2; s2 << age; string s3 = s2.str(); // The str() function will convert a number into a string string answer2 = ""; // For concatenation of strings. answer2 = name + s3; cout << answer2 << endl; return 0; }
在c++ 11中,你可以使用std::to_string,例如:
auto result = name + std::to_string( age );
常见答案:itoa()
这很糟糕。正如这里指出的,Itoa是非标准的。
如果有Boost,可以使用Boost::lexical_cast<std::string>(age)将整数转换为字符串。
另一种方法是使用stringstreams:
std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;
第三种方法是使用C库中的sprintf或snprintf。
char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;
其他海报建议使用itoa。这不是一个标准函数,所以如果你使用它,你的代码将不能移植。有些编译器不支持它。
有更多的选项可以用来连接整数(或其他数字对象)与字符串。它就是Boost。格式
#include <boost/format.hpp>
#include <string>
int main()
{
using boost::format;
int age = 22;
std::string str_age = str(format("age is %1%") % age);
}
还有Boost的Karma。精神(v2)
#include <boost/spirit/include/karma.hpp>
#include <iterator>
#include <string>
int main()
{
using namespace boost::spirit;
int age = 22;
std::string str_age("age is ");
std::back_insert_iterator<std::string> sink(str_age);
karma::generate(sink, int_, age);
return 0;
}
提振。Spirit Karma声称是整数到字符串转换的最快选择之一。