免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 12855 | 回复: 3

[C++] <string>中的string类如何利用分隔符(空格)得到想要的字符串子串?谢谢! [复制链接]

论坛徽章:
0
发表于 2009-10-27 19:26 |显示全部楼层
5可用积分
例如字符串str为如下:
a   1            3    2 3
两项之间所间隔的空格数不一定,如何得到第2项呢?有没有什么快捷的方法调用?谢谢!

最佳答案

查看完整内容

#include #include using namespace std;int main(int argc, char* argv[]){ const string from_str = "a 1 3 2 3"; istringstream istr(from_str); string word; int n; cout word) if (cnt++ == n) break; cout

论坛徽章:
0
发表于 2009-10-27 19:26 |显示全部楼层

回复 #1 richardzhang 的帖子

#include <iostream>
#include <sstream>
using namespace std;

int main(int argc, char* argv[])
{
    const string from_str = "a   1            3    2 3";
    istringstream istr(from_str);
    string word;
    int n;
    cout << "the string is: " << from_str << endl;
    cout << "select a word: ";
    cin >> n;
    int cnt = 1;
    while (istr >> word)
        if (cnt++ == n)
          break;
    cout << "the " << n << " word is: " << word << endl;
    return 0;
}

论坛徽章:
0
发表于 2009-10-27 20:53 |显示全部楼层
除了LS的方法,还可以使用getline来提取子串(也适用于非空格分隔符)

论坛徽章:
0
发表于 2009-10-28 10:46 |显示全部楼层
char *str = "a   1            3    2 3"
char str1[6];
char st2[6];
char st3[6];
char st4[6];
char str5[6];
sscanf( str, "%s%s%s%s%s", str1, str2, str3, str4, str5 );
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP