zoukankan      html  css  js  c++  java
  • C++ istringstream总结

    问题描述:

    假如有一行用空格隔开的字符串的话,如何提取出每一个字符串

    比如输入

    abc def ghi

    然后我们又需要存下来每一个字符串的话,需要怎么做。

    方法一:双指针算法。

     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 int main() {
     4     char str[1010];
     5     cin.getline(str, 1010);
     6     int len = strlen(str);
     7     //cout << len << endl;
     8     for (int i = 0; i < len; i++) {
     9         int j = i;
    10         //每一次i循环的时候,都保证i是指向单词的第一个位置
    11         while (j < len && str[j] != ' ') { //只要j没有走到终点  
    12             //然后我们要找到当前这个单词的最后一个位置    
    13             j++;
    14         }
    15         //当while循环结束时,j就指向当前这个空格
    16         //此时从i到j-1之间就是一个单词 
    17         //这道题的具体逻辑 
    18         for (int k = i; k < j; k++) {
    19             cout << str[k];
    20         } 
    21         cout << endl;
    22         i = j;
    23         //cout << j << endl; 
    24     }
    25     return 0;
    26 }

    运行结果:

     方法二:C++中的istringstream

    具体用法如下:

     1 #include <bits/stdc++.h> 
     2 using namespace std;  
     3 int main()   {  
     4     string str = "aa bb cc dd ee";  
     5     istringstream is(str); //创建istringstream对象is
     6                           //并同时使is和字符串str绑定 
     7     string s;  
     8     while (is >> s) { //将从str中读取到的字符串is写入到字符串s 
     9         cout << s << endl;  
    10     }  
    11     return 0; 
    12 }

    运行结果:

     适用于istringstream的具体题目https://www.cnblogs.com/fx1998/p/12730320.html

  • 相关阅读:
    C++ 11 Lambda表达式
    Hello word!
    nginx 官方文档翻译
    Http读书笔记1-5章
    ROM、RAM、DRAM、SRAM和FLASH的区别
    优化专题
    Typescript学习
    canvas实现的粒子效果
    【转载】js常用方法和片段
    【转载】图解正向代理、反向代理、透明代理
  • 原文地址:https://www.cnblogs.com/fx1998/p/12868788.html
Copyright © 2011-2022 走看看