C++: Articles:Split a String

切割字符串

  • short article
  • 1
  • 2: 修改方案
    • 2.1 完整的代码

short article

  • 在这篇短文中,我想分享一段关拆分字符串的短代码。
  • 有一个名为explode()的函数可以通过给定的分隔符(单个字符或子字符串)来分割字符串。
  • 例如,给定字符串str=“快速棕色狐狸”将被“”(空格字符)分割。简单地说,我们只需调用explore(str,“”),函数就会返回字符串数组{“the”、“quick”、“brown”、“fox”}。

Foollowing is the definition of explode(using C++ 11)

#include   
#include   
#include   
using namespace std;  
  
  
const vector<string> explode(const string& str, const char& c)
{
	
	string buff{""};
	vector<string> v;
	for(auto n:str)
	{
		if(n != c) buff +=n;
		else {
			if(n ==c && buff != "")
			{
			    v.push_back(buff);
			    buff = "";
            }
        }
    }
    if(buff != "")  v.push_back(buff);
}

int main(){
	string str{"the quick brown fox jumps over the lazy dog"};
    // error : nvalid conversion from 'const char*' to 'char'
	vector<string> vec {explode(str," ")};
	// for(auto n :vec) std::cout << n <
	return 0;
}


上面的代码编译器会报如下错误
error : nvalid conversion from 'const char’ to ‘char’*
下面我分析下:编译器报上述错误的原因

1

2: 修改方案

我们可以将函数 explode的第二个 argument参数修改为 指针 。
即函数原型
const vector explode(const string& str, const char c*){}

2.1 完整的代码

#include   
#include   
#include   
using namespace std;  
  
  
const vector<string> explode(const string& str, const char* c)
{
	
	string buff{""};
	vector<string> v;
	for(auto n:str)
	{
		if(n !=*c) buff +=n;
		else {
			if(n ==*c && buff != "")
			{
			    v.push_back(buff);
			    buff = "";
            }
        }
    }
    if(buff != "")  v.push_back(buff);
	return v;
}

int main(){
	string str{"the quick brown fox jumps over the lazy dog"};
    vector<string> v = explode(str," ");
	vector<string> vec {v};
	for(auto n :vec) std::cout << n <<std:: endl;
	return 0;
}

输出:
  the
quick
brown
fox
jumps
over
the
lazy
dog

你可能感兴趣的:(#,C++,标准库学习,c++,切割字符串)