天天看點

【一個按标志分拆字元串的好方法】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;
}