频道栏目
首页 > 资讯 > C++ > 正文

[一个按标志分拆字符串的好方法]strtok函数简介及应用。

13-01-29        来源:[db:作者]  
收藏   我要投稿
刚刚接触strtok函数,感觉十分神奇。
 
定义:
 
strtok
语法:
 
 
  #include <string.h>
  char *strtok( char *str1, const char *str2 );
功能:函数返回字符串str1中紧接“标记”的部分的指针, 字符串str2是作为标记的分隔符。如果分隔标记没有找到,函数返回NULL。为了将字符串转换成标记,第一次调用str1 指向作为标记的分隔符。之后所以的调用str1 都应为NULL。
 
例如:
 
 
 
[cpp]  
char str[] = "now # is the time for all # good men to come to the # aid of their country";  
   char delims[] = "#";  
   char *result = NULL;  
  
  
  
   result = strtok( str, delims );  
  
  
  
   while( result != NULL ) {  
       printf( "result is \"%s\"\n", result );  
        result = strtok( NULL, delims );  
   }  
这个样例的结果为:
 
result is "now "
result is " is the time for all "
result is " good men to come to the "
result is " aid of their country"
 
实现了通过'#'分拆的目的。
 
典型应用,如HDU 1106:点击打开题目链接
 
 要求按5为分割进行拆解字符串,并转换为字符串进行排序。一般的方法为直接模拟,但是如果灵活使用字符串分割函数strtok(注意它的返回值是指针),字符串转数字函数atoi(),这个题十分简单。
 
[cpp]  
#include <iostream>  
#include <algorithm>  
#include <cstring>  
#include <string>  
#include <string.h>  
#include <stdlib.h>  
using namespace std;  
  
bool cmp(int a,int b)  
{  
    return a<b;  
}  
  
int num[1009];  
  
int main()  
{  
    char tar[1009];  
    while(cin>>tar)  
    {  
        string numpack[1000];  
        memset(num,0,sizeof(num));  
        int pos=0;  
        int start=0,end=0;  
          
        char *temp;  
          
        temp=strtok(tar,"5");   //按5分开也  
          
        while(temp!=NULL)  
        {  
             numpack[pos]=temp;  
             temp=strtok(NULL,"5");  //基本用法 ,把指针存入数组中   
             pos++;              
        }   
          
          
          
        for(int i=0;i<pos;i++)  
        {  
            num[i]=atoi(numpack[i].c_str());  
        }  
              
        sort(num,num+pos,cmp);  
          
        for(int i=0;i<pos;i++)  
        {  
            cout<<num[i];  
            if(i!=pos-1)  
                cout<<" ";  
            else  
                cout<<endl;  
        }  
      
          
    }  
      
    return 0;  
}  
 
相关TAG标签
上一篇:明星营销手段分析
下一篇:SSH无密码验证登录的实现
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站