概述

在C++中, 定义了三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作。

应用

笔者在解答力扣第8题字符串转换整数 (atoi)时便采用了这一方法进行解答。

  1. class Solution {
  2. public:
  3. int myAtoi(string str) {
  4. stringstream sstream;
  5. int ret = 0;
  6. sstream << str;
  7. sstream >> ret;
  8. return ret;
  9. }
  10. };

or

  1. class Solution {
  2. public:
  3. int myAtoi(string s) {
  4. if(s == "")
  5. return 0;
  6. stringstream ss(s);
  7. int ret = 0;
  8. ss >> ret;
  9. return ret;
  10. }
  11. };

当然在实际变成时,我们还是尽量使用系统自带的标准库吧

  1. // Convert string to digit
  2. #include <iostream>
  3. #include <string>
  4. int main()
  5. {
  6. std::string s = "10";
  7. //use stoi convert string to digit
  8. int i = std::stoi(s);
  9. }

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 reserve member function to allocate a large space for expansion. If you’re only concatenating strings use string::append (or string::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_string which can be used to convert numeric types to strings.