You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现每3行字符串合并分组的技术求助

It looks like your current code has two main issues preventing it from meeting your requirements:

  1. The loop with i +=3 is redundant because you're replacing all newlines in the entire string every iteration—this just ends up removing all line breaks regardless of grouping.
  2. It doesn't handle removing the spaces after commas (like turning A2, 10.22 into A2,10.22) as shown in your desired output.

Here's a corrected approach that merges every 3 lines into a group, cleans up the comma spacing, and produces the result you want:

// Assume 'a' is your original input string with newlines
string[] lines = a.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
List<string> mergedGroups = new List<string>();

for (int i = 0; i < lines.Length; i += 3)
{
    // Grab up to 3 lines for the current group
    var currentGroup = lines.Skip(i).Take(3);
    
    // Clean each line: remove spaces after commas and trim extra whitespace
    var cleanedLines = currentGroup.Select(line => line.Replace(", ", ",").Trim());
    
    // Merge the group into a single string with spaces between entries
    string mergedGroup = string.Join(" ", cleanedLines);
    mergedGroups.Add(mergedGroup);
}

// If you want each group on a new line:
richTextBox1.Text = string.Join(Environment.NewLine, mergedGroups);

// OR, if you want everything in one single line (like your example):
// richTextBox1.Text = string.Join(" ", mergedGroups);

How this works:

  • Splitting lines: We split the input string into individual lines and ignore any empty lines (in case the string ends with a newline).
  • Grouping by 3: The loop steps through lines in increments of 3, grabbing up to 3 lines each time (handles incomplete groups at the end).
  • Cleaning formatting: Replace(", ", ",") removes spaces after commas, and Trim() eliminates leading/trailing whitespace from each line.
  • Merging groups: Each cleaned group is joined into a single string, then all groups are combined (either with newlines or spaces, based on your preference).

This will produce exactly the formatted output you showed, while respecting your requirement to group every 3 lines.

内容的提问来源于stack exchange,提问作者Wuhu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:27:34