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

刚刚接触strtok函数,感觉十分神奇。

定义:

strtok

语法:

 
  #include <string.h>
  char *strtok( char *str1, const char *str2 );

功能:函数返回字符串str1中紧接“标记”的部分的指针, 字符串str2是作为标记的分隔符。如果分隔标记没有找到,函数返回NULL。为了将字符串转换成标记,第一次调用str1 指向作为标记的分隔符。之后所以的调用str1 都应为NULL。

例如:


 
 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(),这个题十分简单。

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值