在 C# 中第 n 次出现特殊字符时添加换行符

Add new line character on nth occurrence of a special character in C#

考虑一下我有一个包含这么多竖线分隔数据的字符串。

String s="hskdhkdh|eeeee|eeeee|eeeee|eeeesds|ddd\nsdsfdfdf|dsfdfdf|dfdsf\ndsfdsf|sdfsfdsfds|cvcxvv|hkdh\nhdskdh|hdkshdkd|n\nkho|jljoas|sbkhash|bkshoshak\nhksashalsha|bkgaskgask|hkhlv|skhgdskdg|bgdsjdgsj|gklgau"

我这个字符串,有太多的换行符(\n),但我只想在每第6次出现管道(|)之前使用\n

所以结果应该是

  String s="hskdhkdh|eeeee|eeeee|eeeee|eeeesds|ddd\nsdsfdfdf|dsfdfdf|dfdsfdsfdsf|sdfsfdsfds|cvcxvv|hkdh\nhdskdh|hdkshdkd|nkho|jljoas|sbkhash|bkshoshak\nhksashalsha|bkgaskgask|hkhlv|skhgdskdg|bgdsjdgsj|gklgau"

我正在使用 C#.. 在控制台应用程序中 有人可以帮我吗

var bits = s.Split('|'); // Divide into bits
for(int i = 0; i < bits.Length; i++){
  if(i % 6 == 0){
    bits[i] += "\n";
  }
}
var done = string.Join(bits, '|');

这应该可以(如果编译成功,我直接在回复中编码)

您最好的选择可能是使用 string.split() 方法将其更改为 substringsarray,然后使用 Stringbuildercounter 变量来拆分字符串。

我将使用您的字符串编写下面的代码。

 string s = "hskdhkdh | eeeee | eeeee | eeeee | eeeesds | ddd | sdsfdfdf | dsfdfd | dfdsfdsfdsf | sdfsfdsfds | cvcxvv | hkdh | hdskdh | hdkshdkd | nkho | jljoas | sbkhash | bkshoshak | hksashalsha | bkgaskgask | hkhlv | skhgdskdg | bgdsjdgsj";

        string[] substrings = s.Split('|');

        int counter = 1;

        StringBuilder sb = new StringBuilder();

        foreach (string sub in substrings)
        {
            sb.Append(sub + "|");

            if (counter % 6 == 0)
            {
                sb.Append("\n");
            }

            counter++;
        }

        s = sb.ToString();

您可以尝试使用 Linq:

  String s =
     "hskdhkdh|eeeee|eeeee|eeeee|eeeesds|ddd\nsdsfdfdf|dsfdfdf|dfdsf\ndsfdsf|sdfsfdsfds|cvcxvv|hkdh\nhdskdh|hdkshdkd|n\nkho|jljoas|sbkhash|bkshoshak\nhksashalsha|bkgaskgask|hkhlv|skhgdskdg|bgdsjdgsj|gklgau";

  // Split by | 
  // Remove extra \n 
  // Join back by |
  String result = String.Join("|", s
    .Split('|')
    .Select((item, index) => ((index > 0) && (index % 5 == 0)) 
               ? item 
               : item.Replace("\n", "")));

  // Test:
  // hskdhkdh|eeeee|eeeee|eeeee|eeeesds|ddd
  // sdsfdfdf|dsfdfdf|dfdsfdsfdsf|sdfsfdsfds|cvcxvv|hkdh
  // hdskdh|hdkshdkd|nkho|jljoas|sbkhash|bkshoshak
  // hksashalsha|bkgaskgask|hkhlv|skhgdskdg|bgdsjdgsj|gklgau
  Console.Write(result);