stdstring

How to concatenate a std::string and an int?

让人想犯罪 __ 提交于 2019-11-25 22:32:40
问题 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\" ? 回答1: In alphabetical order: 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

What&#39;s the best way to trim std::string?

隐身守侯 提交于 2019-11-25 22:21:25
问题 I\'m currently using the following code to right-trim all the std::strings in my programs: std::string s; s.erase(s.find_last_not_of(\" \\n\\r\\t\")+1); It works fine, but I wonder if there are some end-cases where it might fail? Of course, answers with elegant alternatives and also left-trim solution are welcome. 回答1: EDIT Since c++17, some parts of the standard library were removed. Fortunately, starting with c++11, we have lambdas which are a superior solution. #include <algorithm>