C++分割字串,及strtok函式使用

Curtis_發表於2019-03-20

一、使用strtok分割字元陣列:

1、strtok函式原型:

char * strtok (char * str, const char * delimiters); 

①、引數str指向要分割的字串,引數delimiters則為分割依據。當發現分割字元時,將該字元改為'\0'字元。

②、在第一次呼叫時,strtok()需給出引數str字串,將字串轉換成標記。

③、往後的呼叫則將引數str設定成NULL。

④、每次呼叫成功則返回下一個分割後的字串指標。 如果已無從分割則返回NULL。

⑤、只能以單個字元最為分割依據(可以有多個依據)。

2、程式碼: 

//藉助strtok實現split
#include<iostream>
#include <cstring>
using namespace std;

int main()
{
    char s[] = "Hello    Nice, to meet  ,* you";
    /*
    ** 用 空格,星號,逗號進行分割 
    ** 無論多少個,都會被當作一個key
    */
    const char* d = "  *,";   //分割依據 
    char *p;  //儲存每次分割結果 
    p = strtok(s,d);      
    
    while(p)
    {
    	cout<<p<<endl;
        p=strtok(NULL,d);		   
    }
        
    return 0;
}

3、結果: 

  • 加深理解:
#include<iostream>
#include <cstring>
using namespace std;

int main()
{
    char s[] = "Hello    Nice, to meet  ,* you";
    
    const char* d = "  *,";   //分割依據 
    char *p;  //儲存每次分割結果 
    //第一次呼叫需引數s 
    p = strtok(s,d);    
    cout<<p<<endl;
    //後面的呼叫,引數為NULL 
    p=strtok(NULL,d);
    cout<<p<<endl;
    
    return 0;
}

 

二、利用find函式與substr函式,實現分割字串:

1、兩個基本函式:

①、find函式用法一: 

1)兩個引數: 

size_type find( const basic_string &str, size_type index );

      str:尋找依據,即要尋找什麼;

      index:從哪裡開始尋找

2)一個引數:

      一個引數,預設從第一個字元開始尋找。

3)未找到則返回string::npos;

②、substr函式用法: 

basic_string substr( size_type index, size_type num = npos );

index:子串起始位置

num:子串長度

2、程式碼:

#include<iostream>
#include<cstring>
#include<vector>
using namespace std;

/*
*str:要分割的字串 
*pattern:分割依據
*result:分割結果 
*/ 

//const保證不改變原串,&不用建立新的字串 
vector<string> splitString(const string& str,const string& pattern)
{
	vector<string> result;
	//string::size_type型別,left:左邊界位置  right:右邊界位置 
	string::size_type left, right;
	
	right = str.find(pattern);
	left = 0;
	
	while(right != string::npos)
  	{
  		//以免字串首部就是分割依據,壓入長度為0的字串 
  		if(right-left)
  		{
  			//壓入起始位置為left,長度為(right-left)的字串 
    		result.push_back(str.substr(left, right-left)); 
  		}	
    	left = right + pattern.size();   //右邊界右移分割依據的長度,作為新的左邊界 
    	right = str.find(pattern, left);   //從left這個位置開始find 
  	}
  	
  	//退出迴圈時,左邊界不是最後一個元素 
  	if(left != str.length())
  	{
  		result.push_back(str.substr(left));
  	}
  	
  	return result;    	
}


int main()
{
	string arrA="cd ab cdcdefcdm ncd";
	string arrB="cd";
	
	vector<string> res=splitString(arrA,arrB);
	
	int len=res.size();
	for(int i=0;i<len;i++)
	{
		cout<<res[i]<<" ";
	}
	
	cout<<"END";
	return 0;
}

3、結果:

 

 

相關文章