C++的字符串分割函數


原文:

C++的字符串沒有分割函數,因此需要自己寫方便使用。而受到開發工具的影響,有很多用起來比較麻煩啦,下面這個比較不錯奧。

 

用STL進行字符串的分割 


涉及到string類的兩個函數find和substr:
1、find函數
原型:size_t find ( const string& str, size_t pos = 0 ) const;
功能:查找子字符串第一次出現的位置。
參數說明:str為子字符串,pos為初始查找位置。
返回值:找到的話返回第一次出現的位置,否則返回string::npos 


2、substr函數
原型:string substr ( size_t pos = 0, size_t n = npos ) const;
功能:獲得子字符串。
參數說明:pos為起始位置(默認為0),n為結束位置(默認為npos)
返回值:子字符串 


實現如下:

 

/*
File : split1.cpp
Author : Mike
E-Mail : Mike_Zhang@live.com
*/
#include <iostream>
#include <string>
#include <vector>

//字符串分割函數
std::vector<std::string> split(std::string str,std::string pattern)
{
std::string::size_type pos;
std::vector<std::string> result;
str+=pattern;//擴展字符串以方便操作
int size=str.size();

for(int i=0; i<size; i++)
{
pos=str.find(pattern,i);
if(pos<size)
{
std::string s=str.substr(i,pos-i);
result.push_back(s);
i=pos+pattern.size()-1;
}
}
return result;
}

int main()
{
std::string str;
std::cout<<"Please input str:"<<std::endl;
//std::cin>>str;
getline(std::cin,str);
std::string pattern;
std::cout<<"Please input pattern:"<<std::endl;
//std::cin>>pattern;
getline(std::cin,pattern);//用於獲取含空格的字符串
std::vector<std::string> result=split(str,pattern);
std::cout<<"The result:"<<std::endl;
for(int i=0; i<result.size(); i++)
{
std::cout<<result[i]<<std::endl;
}

std::cin.get();
std::cin.get();
return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM