C++string分割
4251 ワード
C++の文字列は分割関数がないので、自分で書いて使いやすいようにする必要があります.開発ツールの影響を受けて、使うのが面倒なことがたくさんあります.次はこれがいいですね.
STLによる文字列の分割
stringクラスに関連する2つの関数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)の戻り値:サブ文字列
次のようになります.
STLによる文字列の分割
stringクラスに関連する2つの関数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 : [email protected] */
#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;
}