C++ string和stringstream用法

转自https://blog.csdn.net/sunshineacm/article/details/78068987

一、string

string 是 C++ 提供的字符串类型,和 C 的字串相比,除了有不限长度的优点外,还有其他许多方便的功能。要使用 string, 必须先加入这一行:

#include <string>

接下來要定义一个字串变量,可以写成:

string s;

我们也可以在定义的同时初始化字串:

string s = "you";

而要取得其中某一个字元,和传统C 的字串一样是用 s[i] 的方式取得。比较不一样的是如果 s 有三个字元,传統 C 的字串的 s[3] 是'\0' 字符,但是 C++ 的 string 则是只到 s[2] 这个字符而已。


做一个对照:

操作 string 字符数组
定义字符串
string s; char s[100];
取得第i个字符 s[i] s[i]
字符串长度 s.length()
或 s.size()
strlen(s)
读入一行 getline(cin, s); gets(s);
赋值 s = "you"; strcpy(s, "you");
字符串连接 s = s + "you";
s += "you";
strcat(s, "you");
字符串比较 s == "you" strcmp(s, "you");


两个string常用的方法是find和substr。在下面的代码当中:find函数从str的第3个位置查起,找到ssdf这个子串后,返回子串的位置。而substr函数从pos位置开始,截取5个字符,赋值给str2。也就是说,str2之后的内容将是ssdfs。


  
  
  1. string str = "aaaaddddssdfsasdf";
  2. size_t pos = str.find( "ssdf", 3);
  3. //可以用if(pos == string::npos) 用来判断是否找到子串。
  4. string str2 = str.substr(pos, 5);


二、stringstream

stringstream是 C++ 提供的另一个字串型的串流(stream)物件,和之前学过的iostreamfstream有类似的操作方式。要使用stringstream, 必须先加入这一行:

#include <sstream>

stringstream主要是用在將一个字符串分割,可以先用.clear( )以及.str( )將指定字串设定成一开始的內容,再用>>把个別的资料输出。


举个例子:

題目:输入的第一行有一个数字 N 代表接下來有 N 行资料,每一行资料里有不固定个数的整数(最多20个,每行最大200个字元),编程將每行的总和打印出來。

输入:

3
1 2 3
20 17 23 54 77 60
111 222 333 444 555 666 777 888 999

输出:

6
251
4995


代码:


  
  
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. using namespace std;
  5. int main()
  6. {
  7.      string s;
  8.      stringstream ss;
  9.      int n;
  10.      cin >> n;
  11.     getline( cin, s);  //读取换行
  12.      for ( int i = 0; i < n; i++)
  13.     {
  14.         getline( cin, s);
  15.         ss.clear();
  16.         ss.str(s);
  17.          int sum = 0;
  18.          while ( 1)
  19.         {
  20.              int a;
  21.             ss >> a;
  22.              if(ss.fail())
  23.                  break;
  24.             sum += a;
  25.         }
  26.          cout << sum << endl;
  27.     }
  28.      return 0;
  29. }

三、使用stringstream简化类型转换

C++标准库中的<sstream>提供了比ANSI C的<stdio.h>更高级的一些功能,即单纯性、类型安全和可扩展性。接下来,我将举例说明怎样使用这些库来实现安全和自动的类型转换。

一个例子:


  
  
  1. #include <stdio.h>
  2. int main()
  3. {
  4. int n = 10000;
  5. char s[ 10];
  6. sprintf(s, "%d", n);
  7. //s中的内容为“10000”
  8. //到目前为止看起来还不错。但是,对上面代码的一个微小的改变就会使程序发生错误
  9. printf( "%s\n", s);
  10. sprintf(s, "%f", n);
  11. //错误的格式化符
  12. printf( "%s\n", s);
  13. return 0;
  14. }
输出:


在这种情况下,由于错误地使用了 %f 格式化符来替代了%d。因此,s在调用完sprintf()后包含了一个不确定的字符串。要是能自动推导出正确的类型,那不是更好吗?

进入stringstream:

由于ns的类型在编译期就确定了,所以编译器拥有足够的信息来判断需要哪些转换。<sstream>库中声明的标准类就利用了这一点,自动选择所必需的转换。而且,转换结果保存在stringstream对象的内部缓冲中。你不必担心缓冲区溢出,因为这些对象会根据需要自动分配存储空间。

<sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。简单起见,我主要以stringstream为中心,因为每个转换都要涉及到输入和输出操作。

注意,<sstream>使用string对象来代替字符数组。这样可以避免缓冲区溢出的危险。而且,传入参数和目标对象的类型被自动推导出来,即使使用了不正确的格式化符也没有危险。

1、string到int的转换


  
  
  1. string result = "10000";
  2. int n = 0;
  3. stream << result;
  4. stream >> n; //n等于10000


2.重复利用stringstream对象

如果你打算在多次转换中使用同一个stringstream对象,记住在每次转换前要使用clear()方法。

在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象)对象最大的好处在于效率。stringstream对象的构造和析构函数通常是非常耗费CPU时间的。


3.在类型转换中使用模板

你可以轻松地定义函数模板来将一个任意的类型转换到特定的目标类型。例如,需要将各种数字值,如int、long、double等等转换成字符串,要使用以一个string类型和一个任意值t为参数的to_string()函数。to_string()函数将t转换为字符串并写入result中。使用str()成员函数来获取流内部缓冲的一份拷贝。


  
  
  1. template<class T>
  2. void to_string(string &result, const T &t)
  3. {
  4. ostringstream oss; //创建一个流
  5. oss << t; //把值传递入流中
  6. result = oss.str(); //获取转换后的字符并将其写入result
  7. }
  8. //这样,你就可以轻松地将多种数值转换成字符串了
  9. to_string(s1, 10.5); //double到string
  10. to_string(s2, 123); //int到string
  11. to_string(s3, true); //bool到string
  12. //可以更进一步定义一个通用的转换模板,用于任意类型之间的转换。函数模板convert()含有两个模板参数out_type和in_value,功能是将in_value值转换成out_type类型:
  13. template< class out_type, class in_value>
  14. out_type convert(const in_value & t)
  15. {
  16. stringstream stream;
  17. stream << t; //向流中传值
  18. out_type result; //这里存储转换结果
  19. stream >> result; //向result中写入值
  20. return result;
  21. }
测试代码:


  
  
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. using namespace std;
  5. template< class T>
  6. void to_string(string &result, const T &t)
  7. {
  8. ostringstream oss;
  9. oss << t;
  10. result = oss.str();
  11. }
  12. template< class out_type, class in_value>
  13. out_type convert(const in_value & t)
  14. {
  15. stringstream stream;
  16. stream << t;
  17. out_type result;
  18. stream >> result;
  19. return result;
  20. }
  21. int main()
  22. {
  23. //to_string实例
  24. string s1, s2, s3;
  25. to_string(s1, 10.5); //double到string
  26. to_string(s2, 123); //int到string
  27. to_string(s3, true); //bool到string
  28. cout << s1 << endl << s2 << endl << s3 << endl << endl;
  29. //convert()例子
  30. double d;
  31. string salary;
  32. string s = "12.56";
  33. d = convert < double> (s); //d等于12.56
  34. salary = convert < string> ( 9000.0); //salary等于"9000"
  35. cout << d << endl << salary << endl;
  36. return 0;
  37. }
输出:



4.结论

在过去留下来的程序代码和纯粹的C程序中,传统的<stdio.h>形式的转换伴随了我们很长的一段时间。但是,如文中所述,基于stringstream的转换拥有类型安全和不会溢出这样的特性,使我们有充足得理由去使用<sstream>。<sstream>库还提供了另外一个特性—可扩展性。你可以通过重载来支持自定义类型间的转换。


5.一些实例

stringstream通常是用来做数据转换的。相比c库的转换,它更加安全,自动和直接。

例子一: 基本数据类型转换例子 int 转 string


  
  
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. using namespace std;
  5. int main()
  6. {
  7. stringstream ss;
  8. string s;
  9. int i = 1000;
  10. ss << i;
  11. ss >> s;
  12. cout << s << endl;
  13. return 0;
  14. }

运行结果:



例子二: 除了基本类型的转换,也支持char *的转换


  
  
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. using namespace std;
  5. int main()
  6. {
  7. stringstream ss;
  8. char s[ 10];
  9. ss << 8888;
  10. ss >> s;
  11. cout << s << endl;
  12. return 0;
  13. }

运行结果:



例子三: 再进行多次转换的时候,必须调用stringstream的成员函数.clear()


  
  
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. using namespace std;
  5. int main()
  6. {
  7. stringstream ss;
  8. int first = 0, second = 0;
  9. ss << "456"; // 插入字符串
  10. ss >> first; //转换成int
  11. cout << first << endl;
  12. ss.clear(); //在进行多次转换前, 必须清除ss
  13. ss << true;
  14. ss >> second;
  15. cout << second << endl;
  16. return 0;
  17. }

运行结果:

运行.clear()结果


没有运行.clear()结果



6.使用误区

如果stringstream使用不当,当心内存出问题。试试下面的代码,运行程序前打开任务管理器,看看内存变化。

复制代码,把 stream.str("");  那一行的注释去掉,再运行程序,内存就正常了。


看来stringstream似乎不打算主动释放内存( 或许是为了提高效率 ),但如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消耗,因此这时候,需要适时地清除一下缓冲 ( 用 stream.str("")  )。

另外不要企图用  stream.str().resize(0) 或  stream.str().clear()  来清除缓冲,使用它们似乎可以让stringstream的内存消耗不要增长得那么快,但仍然不能达到清除stringstream缓冲的效果(做个实验就知道了,内存的消耗还在缓慢的增长)


  
  
  1. #include <iostream>
  2. #include <sstream>
  3. using namespace std;
  4. int main()
  5. {
  6. std:: stringstream stream;
  7. string str;
  8. while( 1)
  9. {
  10. //clear()这个名字让很多人想当然地认为它会清除流的内容。
  11. //实际上它并不清空任何内容,它只是重置了流的状态标志。
  12. stream.clear();
  13. //去掉下面这行注释,清空stringstream的缓冲,每次循环内存消耗将不再增加。
  14. //stream.str("");
  15. stream << "you see see you";
  16. stream >> str;
  17. // 去掉下面这行注释,看看每次循环,你的内存消耗会增加多少
  18. //cout << "Size of stream = " << stream.str().length() << endl;
  19. }
  20. return 0;
  21. }

参考链接:

http://blog.csdn.net/zhang_xueping/article/details/47846807

http://blog.csdn.net/u014097230/article/details/52089530


猜你喜欢

转载自blog.csdn.net/u012686154/article/details/83684331