• C++实现字符串分割(类似于Python的split方法)


    先学Python后学其他语言的后遗症就是Python中很多好用的方法在别的语言中都找不到

    所以自己写一个吧

     1 #include "stdafx.h"
     2 #include <iostream>
     3 #include <list>
     4 
     5 void stringSplit(std::string msg, std::string part, std::list<std::string> &result)
     6 {
     7     int msgLen = msg.length();
     8     int partLen = part.length();
     9     int offset = 0;
    10     std::string ele = "";
    11     std::cout << "msg length:" << msgLen << "part length:" << partLen << std::endl;
    12     while (offset < msgLen)
    13     {
    14         int stop = offset + partLen;
    15         std::string piece = msg.substr(offset, partLen);
    16         cout << "piece is " << piece << " offset is " << offset << " stop is " << stop << endl;
    17         if (piece == part)
    18         {
    19             result.push_back(ele);
    20             offset = offset + partLen;
    21             ele = "";
    22         }
    23         else
    24         {
    25             ele = ele + msg[offset];
    26             offset++;
    27         }
    28     }
    29     result.push_back(ele);
    30 }
    31 
    32 // limit 准备分割的次数, 如,2,代表函数发现两次分隔符,就会停止,返回长度为3的列表
    33 void stringSplit(std::string msg, std::string part, std::list<std::string> &result, int limit)
    34 {
    35     int msgLen = msg.length();
    36     int partLen = part.length();
    37     int offset = 0;
    38     std::string ele = "";
    39     std::cout << "msg length:" << msgLen << "part length:" << partLen << std::endl;
    40     int sign = 0;
    41     while (offset < msgLen)
    42     {
    43         int stop = offset + partLen;
    44         std::string piece = msg.substr(offset, partLen);
    45         cout << "piece is " << piece << " offset is " << offset << " stop is " << stop << endl;
    46         if (piece == part)
    47         {
    48             result.push_back(ele);
    49             offset = offset + partLen;
    50             ele = "";
    51             sign++;
    52             if (sign == limit){
    53                 result.push_back(msg.substr(offset, msgLen - offset));
    54                 return;
    55             }
    56         }
    57         else
    58         {
    59             ele = ele + msg[offset];
    60             offset++;
    61         }
    62     }
    63     result.push_back(ele);
    64 }

    对字符串进行一次遍历,每次切取与分隔符等长的一段,如果与分隔符一致,则将前一段字符串放入result,否则,当前位置往后移动一次

  • 相关阅读:
    HTML5新媒体元素
    概述
    (一)最小可行化应用
    JSON
    ajax的工作原理
    R语言学习笔记(四)
    R语言学习笔记(一)
    转:禅道的数据库结构
    转:bug的分类和等级
    转:如何定义 Bug 的优先级
  • 原文地址:https://www.cnblogs.com/haiton/p/15031710.html
Copyright © 2020-2023  润新知