概述
在C++中,
应用
笔者在解答力扣第8题字符串转换整数 (atoi)时便采用了这一方法进行解答。
class Solution {public:int myAtoi(string str) {stringstream sstream;int ret = 0;sstream << str;sstream >> ret;return ret;}};
or
class Solution {public:int myAtoi(string s) {if(s == "")return 0;stringstream ss(s);int ret = 0;ss >> ret;return ret;}};
当然在实际变成时,我们还是尽量使用系统自带的标准库吧
// Convert string to digit#include <iostream>#include <string>int main(){std::string s = "10";//use stoi convert string to digitint i = std::stoi(s);}
string append VS stringstream
如果仅是进行字符串的拼接则最好使用append或者operator+,但是如果想在拼接的过程中,顺便完成数据格式的转换后再拼接,则使用stringstream。
I don’t know which one will be faster, but if I had to guess I’d say your second example is, especially since you’ve called the
reservemember function to allocate a large space for expansion. If you’re only concatenating strings usestring::append(orstring::operator+=).If you’re going to convert numbers to their string representation, as well as format them during conversion, and then append the conversion results together, use stringstreams. I mention the formatting part explicitly because if you do not require formatting C++11 offers
std::to_stringwhich can be used to convert numeric types to strings.
