• C++ 实现 split 操作


    理由:由于 C++ 标准库里面没有字符分割函数 split ,这可太不方便了,我们利用 STL 来实现自己的 split 函数:

    原型:vector<string> split(const string& s, const string& seperator);

     1 // codeThinking.cpp : 定义控制台应用程序的入口点。
     2 //
     3 
     4 #include "stdafx.h"
     5 #include <windows.h>
     6 #include <iostream>
     7 #include <vector>
     8 #include <stack>
     9 #include <cstring>
    10 #include<unordered_map>
    11 
    12 using namespace std;
    13 
    14 vector<string> split(const string& s, const string& seperator) {
    15     vector<string> result;
    16     unsigned int posBegin = 0;
    17     unsigned int posSeperator = s.find(seperator);
    18 
    19     while (posSeperator != s.npos) {
    20         result.push_back(s.substr(posBegin, posSeperator - posBegin));// 
    21         posBegin = posSeperator + seperator.size(); // 分隔符的下一个元素
    22         posSeperator = s.find(seperator, posBegin);
    23     }
    24     if (posBegin != s.length()) // 指向最后一个元素,加进来
    25         result.push_back(s.substr(posBegin));
    26 
    27     return result;
    28 }
    29 
    30 void splitTest(const string& str,string& symbol) {
    31     vector<string> result;
    32     result = split(str, symbol);
    33     for (int i = 0; i < result.size(); ++i) {
    34         cout <<atoi(result[i].c_str())<< endl;  // 把数字字符串转换为 数字
    35     }
    36 }
    37 
    38 int _tmain(int argc, _TCHAR* argv[])
    39 {
    40     string widths = "5 5 5 5 5 5 10 10 10 10 10 10 10 10 10 10 10 10 5 5 5 5 5 5 5 5";
    41     string symbol = " ";
    42 
    43     splitTest(widths,symbol);
    44 
    45 
    46     system("pause");
    47     return 0;
    48 }
    所有博文均为原著,如若转载,请注明出处!
  • 相关阅读:
    1-vue初识
    使用 MegaCLI 检测磁盘状态
    CDH中spark-shell报错: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/fs/FSDataInputStream
    Linux查看服务器公网ip的方法
    Linux sar 查看网卡流量 网络io
    Docker为何需要OS的基础镜像?
    Spark中reduceByKey(_+_)的说明
    ELK
    Navicat Premium 12安装与激活
    数据查询
  • 原文地址:https://www.cnblogs.com/zpcoding/p/10645726.html
Copyright © 2020-2023  润新知