【问题标题】:How to split of string and for each determined character found add a new line如何拆分字符串并为找到的每个确定的字符添加一个新行
【发布时间】:2018-09-02 07:31:39
【问题描述】:

例如:

我有这个:

string commaSeparatedString = "124,45415,1212,4578,233,968,6865,32545,4545";

我想这样做为每 4 个找到逗号添加一个新行

124-45415-1212-4578
233-968-6865-32545
4545

【问题讨论】:

  • 看看string.Split(',')

标签: c# .net string


【解决方案1】:

这个呢:

string str = "124,45415,1212,4578,233,968,6865,32545,4545";
var result = string.Join("-", sss.Split(',').Select((c, index) => (index + 1) % 4 == 0 ?
                              c + Environment.NewLine : c));

别忘了先将LINQ 添加到您的 using 指令中:

using System.Linq;

【讨论】:

  • 你可以这样做:string.Join("", str.Split(',').Select((c, i) => (i != 0) && ((i + 1) % 4 == 0) ? c + Environment.NewLine : c + "-"))
【解决方案2】:

试试这个:

const int batch = 4;
var target = "124,45415,1212,4578,233,968,6865,32545,4545";
var items = target.Split(',');
var results = new List<string>();

var continue = false;
var step = 0;
do
{
    var slide = items.Skip(step++ * batch).Take(batch);
    continue = slide.Count() == batch;
    results.Add(string.Join('-', slide));
}while(continue);

【讨论】:

    【解决方案3】:

    给你:

    using System;
    
    namespace ConsoleApp
    {
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write(SplitOnChar("124,45415,1212,4578,233,968,6865,32545,4545",',',4));
            Console.ReadKey();
        }
    
        private static string SplitOnChar(string input, char theChar, int number)
        {
            string result = "";
            int seen = 0;
            int lastSplitIndex = 0;
    
            for(int i = 0; i< input.Length;i++)
            {
                char c = input[i];
                if (c.Equals(theChar))
                {
                    seen++;
                    if (seen == number)
                    {
                        result += input.Substring(lastSplitIndex + 1, i - lastSplitIndex -1);
                        result += Environment.NewLine;
                        lastSplitIndex = i;
                        seen = 0;
                    }
                }
            }
    
            result += input.Substring(lastSplitIndex + 1);
            result = result.Replace(theChar, '-');
            return result;
        }
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 2023-04-06
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      • 2022-06-13
      • 2017-01-29
      相关资源
      最近更新 更多