I thought this would be really simple, but it's presenting some difficulties. If I have
std::string name = "John";
int age = 21;
How do I combine them to get a single string "John21"
?
I thought this would be really simple, but it's presenting some difficulties. If I have
std::string name = "John";
int age = 21;
How do I combine them to get a single string "John21"
?
アルファベット順:
std::string name = "John";
int age = 21;
std::string result;
// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);
// 2. with C++11
result = name + std::to_string(age);
// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);
// 4. with FastFormat.Write
fastformat::write(result, name, age);
// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);
// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();
// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);
// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);
// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);
// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
#include <string>
)#include <sstream>
です (標準 C++ から)C++11 では、次のように使用できますstd::to_string
。
auto result = name + std::to_string( age );
Boost がある場合は、 を使用して整数を文字列に変換できますboost::lexical_cast<std::string>(age)
。
もう 1 つの方法は、文字列ストリームを使用することです。
std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;
3 番目のアプローチは、C ライブラリを使用するsprintf
かsnprintf
、C ライブラリから取得することです。
char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;
を使用することを提案した他のポスターitoa
。これは標準関数ではないため、使用するとコードは移植できなくなります。それをサポートしていないコンパイラがあります。
#include <iostream>
#include <sstream>
std::ostringstream o;
o << name << age;
std::cout << o.str();
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
stringstream s;
s << i;
return s.str();
}
http://www.research.att.com/~bs/bs_faq2.htmlから恥知らずに盗まれた。
これが最も簡単な方法です:
string s = name + std::to_string(age);
最も簡単な答えは、sprintf
関数を使用することだと私には思えます:
sprintf(outString,"%s%d",name,age);
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
stringstream s;
s << name << i;
return s.str();
}
#include <sstream>
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
次に、使用法は次のようになります
std::string szName = "John";
int numAge = 23;
szName += to_string<int>(numAge);
cout << szName << endl;
Googled [およびテスト済み:p]
+
出力演算子を持つものの連結に使用したい場合は、次のテンプレート バージョンを提供できoperator+
ます。
template <typename L, typename R> std::string operator+(L left, R right) {
std::ostringstream os;
os << left << right;
return os.str();
}
次に、連結を簡単な方法で記述できます。
std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);
std::cout << bar << std::endl;
出力:
the answer is 42
これは最も効率的な方法ではありませんが、ループ内で多くの連結を行う場合を除き、最も効率的な方法は必要ありません。
MFC を使用している場合は、CString を使用できます。
CString nameAge = "";
nameAge.Format("%s%d", "John", 21);
Managed C++ には 文字列フォーマッタもあります。
std::ostringstream は良い方法ですが、書式設定をワンライナーに変換する次の追加のトリックが便利な場合があります。
#include <sstream>
#define MAKE_STRING(tokens) /****************/ \
static_cast<std::ostringstream&>( \
std::ostringstream().flush() << tokens \
).str() \
/**/
これで、次のように文字列をフォーマットできます。
int main() {
int i = 123;
std::string message = MAKE_STRING("i = " << i);
std::cout << message << std::endl; // prints: "i = 123"
}
Qt関連の質問はこれを支持してクローズされたので、Qtを使用してそれを行う方法は次のとおりです。
QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);
文字列変数は、%1 の代わりに someIntVariable の値を持ち、最後に someOtherIntVariable の値を持ちます。
整数 (またはその他の数値オブジェクト) を文字列と連結するために使用できるオプションは他にもあります。Boost.Formatです
#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.Spirit(v2)のKarma
#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;
}
Boost.Spirit Karma は、整数から文字列への変換の最速のオプションの 1 つだと主張しています。
#include <sstream> std::ostringstream s; s << "John " << age; std::string query(s.str());
std::string query("John " + std::to_string(age));
#include <boost/lexical_cast.hpp> std::string query("John " + boost::lexical_cast<std::string>(age));
以下の簡単なトリックを使用して int を文字列に連結できますが、これは整数が 1 桁の場合にのみ機能することに注意してください。それ以外の場合は、その文字列に整数を 1 桁ずつ追加します。
string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;
Output: John5
int 数値をパラメーターとして取り、それを文字列リテラルに変換する、私が書いた関数があります。この関数は、1 桁を対応する char に変換する別の関数に依存しています。
char intToChar(int num)
{
if (num < 10 && num >= 0)
{
return num + 48;
//48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table)
}
else
{
return '*';
}
}
string intToString(int num)
{
int digits = 0, process, single;
string numString;
process = num;
// The following process the number of digits in num
while (process != 0)
{
single = process % 10; // 'single' now holds the rightmost portion of the int
process = (process - single)/10;
// Take out the rightmost number of the int (it's a zero in this portion of the int), then divide it by 10
// The above combination eliminates the rightmost portion of the int
digits ++;
}
process = num;
// Fill the numString with '*' times digits
for (int i = 0; i < digits; i++)
{
numString += '*';
}
for (int i = digits-1; i >= 0; i--)
{
single = process % 10;
numString[i] = intToChar ( single);
process = (process - single) / 10;
}
return numString;
}