在C 中連接字串和整數是一項常見任務,但找到最有效且最有效的方法可能很棘手。簡潔的方法來做到這一點。可以使用多種方法來實現此目的,選擇取決於效能、安全性和平台相容性等因素。
1.使用Boost的lexical_cast:
#include <boost/lexical_cast.hpp> std::string name = "John"; int age = 21; std::string result = name + boost::lexical_cast<std::string>(age);
2.使用C 11 的std::to_string:
:#include <iostream> std::string name = "John"; int age = 21; std::string result = name + std::to_string(age);
3.使用FastFormat.Format
:#include <FastFormat.h> std::string name = "John"; int age = 21; std::string result; fastformat::fmt(result, "{0}{1}", name, age);
4.使用 FastFormat.Write
:#include <FastFormat.h> std::string name = "John"; int age = 21; std::string result; fastformat::write(result, name, age);
5.使用 {fmtf}庫
:#include <fmt/format.h> std::string name = "John"; int age = 21; std::string result = fmt::format("{}{}", name, age);
6.使用IOStreams
:#include <iostream> #include <sstream> std::string name = "John"; int age = 21; std::stringstream sstm; sstm << name << age; std::string result = sstm.str();
7.使用itoa
:#include <cstdio> std::string name = "John"; int age = 21; char numstr[21]; // enough to hold all numbers up to 64-bits std::string result = name + itoa(age, numstr, 10);
7.使用itoa:
#include <cstdio> std::string name = "John"; int age = 21; char numstr[21]; // enough to hold all numbers up to 64-bits sprintf(numstr, "%d", age); std::string result = name + numstr;
8.使用sprintf:
#include <stlsoft/integer_to_string.hpp> std::string name = "John"; int age = 21; char numstr[21]; // enough to hold all numbers up to 64-bits std::string result = name + stlsoft::integer_to_string(numstr, 21, age);
9.使用STLSoft的integer_to_string:
#include <wintlsoft/int_to_string.h> std::string name = "John"; int age = 21; std::string result = name + winstl::int_to_string(age);
10。使用STLSoft的winstl::int_to_string():
#include <Poco/NumberFormatter.h> std::string name = "John"; int age = 21; std::string result = name + Poco::NumberFormatter().format(age);
11。使用 Poco 的 NumberFormatter
:詳細介紹了每種方法的效能、安全性和相容性特徵,以協助您選擇最適合您特定需求的方法。以上是如何在 C 中有效連接字串和整數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!