Strings

1. convert integer a string (float as well)

auto s1 = std::to_string(123);
auto s2 = std::to_string(123.321);
auto s3 = std::to_wstring(123l);
auto s3 = std::to_wstring(123u);

2. convert string to integer type

auto i1 = std::stoi("123");
auto i2 = std::stoi("1010", nullptr, 2);
auto i3 = std::stoi("0xAA", nullptr, 16);

auto d1 = std::stod("123.321");
auto d2 = std::stod("1.23e2");

try {
auto i1 = std::stoi("");//throws invalid_argument
auto i2 = std::stoi("123456789");//throws out_of_range
} catch(std::exception const & e) {
std::cout << e.what() << std::endl;
}

3. using raw strings

auto filepath { R"(C:\Users\Administrator\AppData\)"s };
auto pattern { R"||(\w+)=(\d+)$||"s };

4. replace in STL string using boost

boost::replace_all(sTemp, L"\n", L"");

5. split string using boost


string sHeader = "1;2;3;4";
vector sParts;
boost::split(sParts, sHeader, boost::is_any_of(";"));

6. convert class to string


struct SomeClass	{
	SomeClass() : m_bOne(false), m_bTwo(false) {}
	bool m_bOne;
	bool m_bTwo;

	operator const std::wstring () const {
		std::wostringstream s;
		s	<< L" ONE =" << (m_bOne ? L"yes" : L"no")
			<< L" TWO =" << (m_bTwo ? L"yes" : L"no");
		return s.str();
	}
};

7. format string using boost


std::string firstname, surname;
localizationManager.SetLanguage(Localization::Languages::EN_US);
std::string formattedName{ localizationManager.GetString(Localization::STRING_NAME) };
formattedName = str( boost::format(formattedName) % firstName % surname );

some useful tips (mostly for myself)