[C/C++標準ライブラリ][初級][分割文字列Split]
3692 ワード
シーン:
1.インタフェースは、データを格納するときに文字列値をマージし、特定の特殊文字で部分をマージし、必要に応じて分割する必要がある場合があります.数値や人名など.
2.C++はstrtok,stringstream,find関数で分割を実現する.状況に応じて呼び出すことができます.
20150709:テンプレート追加方式実現
呼び出し方法:
出力:
1.インタフェースは、データを格納するときに文字列値をマージし、特定の特殊文字で部分をマージし、必要に応じて分割する必要がある場合があります.数値や人名など.
2.C++はstrtok,stringstream,find関数で分割を実現する.状況に応じて呼び出すことができます.
void SplitWithFlag(const char* str1,char c,std::vector<std::string>& arr)
{
std::stringstream ss(str1);
string str;
while(getline(ss,str,c))
{
arr.push_back(str);
}
}
20150709:テンプレート追加方式実現
template<class T,typename C>
std::vector<T> SplitChar(T& str,C c)
{
std::vector<T> temp;
typedef std::basic_stringstream<C, std::char_traits<C>,std::allocator<C> > mstringstream;
mstringstream mss;
mss << str;
T s;
while(getline(mss,s,c))
{
temp.push_back(s);
}
return temp;
}
呼び出し方法:
TEST(test_AndroidAssistant,SplitChar)
{
std::wstring str(L"afdadsfasd
asdfasdfa
asdfasdf");
std::vector<std::wstring> arr = SplitChar(str,L'
');
for(int i = 0;i < arr.size();++i)
{
std::wcout << arr[i] << std::endl;
}
std::cout << "................." << std::endl;
std::string str1("afdadsfasd
asdfasdfa
asdfasdf");
std::vector<std::string> arr1 = SplitChar(str1,'
');
for(int i = 0;i < arr1.size();++i)
{
std::cout << arr1[i] << std::endl;
}
}
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
void TestStrtok()
{
//1. , , .
//2. .
//3. .
char c_str[]="google||twitter||facebook||microsoft||apple||ibm||";
const char* delim = "||";
char* result = strtok(c_str,delim);
while(result != NULL)
{
cout << result << endl;
result = strtok(NULL,delim);
}
}
void TestGetLineWithStringStream()
{
//1. ,
stringstream ss("google|twitter|facebook|microsoft|apple|ibm|");
string str;
while(getline(ss,str,'|'))
{
cout << str << endl;
}
}
void TestStringFind()
{
//1. , , . .
string str = "google||twitter||facebook||microsoft||apple||ibm||";
const char* delim = "||";
const int len = strlen(delim);
size_t index = 0;
size_t pos = str.find(delim,index);
while(pos != string::npos)
{
string ss = str.substr(index,pos-index);
cout << ss << endl;
index = pos+len;
pos = str.find(delim,index);
}
//cout << "is last?" << " index:" << index << " str.length():" << str.length() << endl;
if((index+1) < str.length())
{
string ss = str.substr(index,str.length() - index);
cout << ss << endl;
}
}
int main(int argc, char const *argv[])
{
cout << "TestStrtok: " << endl;
TestStrtok();
cout << "TestGetLineWithStringStream: " << endl;
TestGetLineWithStringStream();
cout << "TestStringFind: " << endl;
TestStringFind();
return 0;
}
// : 1.http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c
出力:
TestStrtok:
google
twitter
facebook
microsoft
apple
ibm
TestGetLineWithStringStream:
google
twitter
facebook
microsoft
apple
ibm
TestStringFind:
google
twitter
facebook
microsoft
apple
ibm
[Finished in 0.2s]