用c++如何取出字符串中的单词?

terry_v 2011-04-28 02:51:24
假设:
string str="hello;good;word;nihao";
现在要求取出str中的每个单词;
用c++如何实现呢?
...全文
1300 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
helww 2011-04-28
  • 打赏
  • 举报
回复

#include <string>
#include <iostream>

using namespace std;

int main()
{
string str="hello;good;word;nihao";

string str2[10];
string::size_type first=0,end=0;
int i=0;

while(1)
{
if( (end=str.find(";",first)) != string::npos)
{
str2[i++]=str.substr(first,end-first);
first=end+1;
}
else
break;
}

str2[i]=str.substr(first,str.size()-first);

return 0;
}

Defonds 2011-04-28
  • 打赏
  • 举报
回复
办法很多。依次截取、遍历
pathuang68 2011-04-28
  • 打赏
  • 举报
回复

#include <string.h>
#include <stdio.h>

char string[] = "A string\tof ,,tokens\nand some more tokens";
char seps[] = " ,;\t\n"; // 各种分隔符号都可以
char *token;

void main( void )
{
printf( "%s\n\nTokens:\n", string );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s\n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}
bargio_susie 2011-04-28
  • 打赏
  • 举报
回复
int Split(const string &str, const string &splitchar, vector <string> &vec)
{
string stmp = "";
string::size_type pos = 0, prev_pos = 0;
int j = 0;
vec.clear();
while ((pos = s.find_first_of(splitchar, pos)) != string::npos)
{
stmp = s.substr(prev_pos, pos - prev_pos);
vec.push_back(stmp);
prev_pos = ++pos;
}
stmp = s.substr(prev_pos, pos - prev_pos);
if (stmp.length() > 0)
{
vec.push_back(stmp);
}
return 0;
}


Split(str, ";", svec);
luciferisnotsatan 2011-04-28
  • 打赏
  • 举报
回复
或者就用string的find函数系列和substr函数
luciferisnotsatan 2011-04-28
  • 打赏
  • 举报
回复
先复制到一个char数组里,然后用 strtok
jackzhhuang 2011-04-28
  • 打赏
  • 举报
回复
一个个遍历,依次放到一个string,遇到;就轮到下个单词

或者用boost的正则表达式库,顺便可以学习正则表达式,呵呵。

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧