zoukankan      html  css  js  c++  java
  • C#字符串处理之分割字符串并保留分隔符的几种方法

    目录

    • [方法一]

        string[] parts = Regex.Split(originalString, @"(?<=[.,;])")
      
    • [方法二]

        public static IEnumerable<string> SplitAndKeep(this string s, char[] delims)
        {
      int start = 0, index;
      
      while ((index = s.IndexOfAny(delims, start)) != -1)
      {
          if(index-start > 0)
              yield return s.Substring(start, index - start);
          yield return s.Substring(index, 1);
          start = index + 1;
      }
      
      if (start < s.Length)
      {
          yield return s.Substring(start);
      }
        }
      
    • [方法三]

        public static IEnumerable<string> SplitAndKeep(string s, params string[] delims)
        {
          var rows = new List<string>() { s };
          foreach (string delim in delims)//delimiter counter
          {
              for (int i = 0; i < rows.Count; i++)//row counter
              {
                  int index = rows[i].IndexOf(delim);
                  if (index > -1
                      && rows[i].Length > index + 1)
                  {
                      string leftPart = rows[i].Substring(0, index + delim.Length);
                      string rightPart = rows[i].Substring(index + delim.Length);
                      rows[i] = leftPart;
                      rows.Insert(i + 1, rightPart);
                  }
              }
          }
          return rows;
      }
      

    具体可参考:https://stackoverflow.com/questions/521146/c-sharp-split-string-but-keep-split-chars-separators

  • 相关阅读:
    SpringBoot启动配置原理
    SpringBoot和web开发
    SpringBoot和日志
    SpringBoot入门
    Docker仓库
    Docker Swarm
    Docker相关概念
    Docker服务编排
    Dockerfile
    Docker应用部署
  • 原文地址:https://www.cnblogs.com/wecc/p/11360668.html
Copyright © 2011-2022 走看看