Chinaunix首页 | 论坛 | 博客
  • 博客访问: 504339
  • 博文数量: 184
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1172
  • 用 户 组: 普通用户
  • 注册时间: 2016-06-21 13:40
个人简介

技术改变命运

文章分类

全部博文(184)

文章存档

2020年(16)

2017年(12)

2016年(156)

我的朋友

分类: C/C++

2016-09-23 18:52:40

char *strtok(char s[], const char *delim);

点击(此处)折叠或打开

  1. #include<iostream>
  2. #include<string.h>
  3. #include<string>
  4. using namespace std;
  5. int main()
  6. {
  7.     char str[] = "Hello world";
  8.     char *token = strtok(str," ");
  9.     //cout << token << endl;
  10.     while (token != NULL)
  11.     {
  12.         string s(token);
  13.         token = strtok(NULL," ");
  14.         cout << s << endl;
  15.     }
  16.     return 0;
  17. }
输出:
[root@localhost c++]# ./a.out
Hello
world
应用:删除重复字符串


点击(此处)折叠或打开

  1. #include<iostream>
  2. #include<map>
  3. #include<string.h>
  4. #include<string>
  5. using namespace std;
  6. int main()
  7. {
  8.     char str[200] = {0};
  9.     char strbak[200] = {0};
  10.     char *token = NULL;
  11.     map<string,int> wordMap;
  12.     string output;
  13.     int i = 0,j = 0;
  14.     gets(str);
  15.     for (int i = 0;str[i] != '\0';i++)
  16.     {
  17.         if (str[i] == ',' || str[i] == ' ')
  18.         {
  19.             strbak[j] = ' ';
  20.             j++;
  21.         }
  22.         else
  23.         {
  24.             strbak[j] = str[i];
  25.             j++;
  26.         }
  27.     }
  28.     strbak[j] = '\0';
  29.     strncpy(str,strbak,sizeof(strbak)+1);
  30.     token = strtok(str," ");
  31.     while (token != NULL)
  32.     {
  33.         string s(token);
  34.         wordMap[s]++;
  35.         token = strtok(NULL," ");
  36.     }
  37.     int count = 0;
  38.     token = strtok(strbak," ");
  39.     while (token != NULL)
  40.     {
  41.         string s(token);
  42.         if (wordMap[s] >= 1)
  43.         {
  44.             if (count == 0)
  45.             {
  46.                 output = output+s;
  47.                 wordMap[s] = 0;
  48.             }
  49.             else
  50.             {
  51.                 output = output+" "+s;
  52.                 wordMap[s] = 0;
  53.             }
  54.             count++;
  55.         }
  56.         token = strtok(NULL," ");
  57.     }
  58.     cout << output<< endl;
  59.     return 0;
  60. }
运行结果:
[root@localhost c++]# ./a.out
i love love zhouyi
i love zhouyi


阅读(1453) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~