zoukankan      html  css  js  c++  java
  • C++常用的string字符串截断函数

    C++中经常会用到标准库函数库(STL)的string字符串类,跟其他语言的字符串类相比有所缺陷。这里就分享下我经常用到的两个字符串截断函数:

    #include <iostream>
    #include <vector>
    #include <string>
    #include <sstream>
    
    using namespace std;
    
    //根据字符切分string,兼容最前最后存在字符
    void CutString(string line, vector<string> &subline, char a)
    {
    	//首字母为a,剔除首字母
    	if (line.size() < 1)
    	{
    		return;
    	}
    	if (line[0] == a)
    	{
    		line.erase(0, 1);
    	}
    
    	size_t pos = 0;
    	while (pos < line.length())
    	{
    		size_t curpos = pos;
    		pos = line.find(a, curpos);
    		if (pos == string::npos)
    		{
    			pos = line.length();
    		}
    		subline.push_back(line.substr(curpos, pos - curpos));
    		pos++;
    	}
    
    	return;
    }
    
    //根据空截断字符串
    void ChopStringLineEx(string line, vector<string> &substring)
    {
    	stringstream linestream(line);
    	string sub;
    
    	while (linestream >> sub)
    	{
    		substring.push_back(sub);
    	}
    }
    
    int main()
    {
    	string line = ",abc,def,ghi,jkl,mno,";
    	vector<string> subline;
    	char a = ',';
    	CutString(line, subline, a);
    	cout << subline.size()<<endl;
    	for (auto it : subline)
    	{
    		cout << it << endl;
    	}
    
    	cout << "-----------------------------" << endl;
    
    	line = "   abc   def   ghi  jkl  mno ";
    	subline.clear();	
    	ChopStringLineEx(line, subline);
    	cout << subline.size() << endl;
    	for (auto it : subline)
    	{
    		cout << it << endl;
    	}
    
    
        return 0;
    }
    

    函数CutString根据选定的字符切分string,兼容最前最后存在字符;函数ChopStringLineEx根据空截断字符串。这两个函数在很多时候都是很实用的,例如在读取文本的时候,通过getline按行读取,再用这两个函数分解成想要的子串。

  • 相关阅读:
    hdu4277 暴力
    hdu4271 Find Black Hand 2012长春网络赛E题 最短编辑距离
    poj3356 字符串的最小编辑距离 dp
    HDU4267 A Simple Problem with Integers 线段树/树状数组
    树链剖分 模版
    SPOJ375 Query on a tree 树链剖分
    Orz_panda cup I题 (xdoj1117) 状压dp
    27号的十道离线线段树
    The 2015 "Orz Panda" Cup Programming Contest
    codeforces #274 C. Riding in a Lift dp+前缀和优化
  • 原文地址:https://www.cnblogs.com/charlee44/p/11210009.html
Copyright © 2011-2022 走看看