C#实现每3行字符串合并分组的技术求助
It looks like your current code has two main issues preventing it from meeting your requirements:
- The loop with
i +=3is redundant because you're replacing all newlines in the entire string every iteration—this just ends up removing all line breaks regardless of grouping. - It doesn't handle removing the spaces after commas (like turning
A2, 10.22intoA2,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, andTrim()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
相关产品推荐
相关产品推荐

