C# 如何以另一数组的元素为分隔符拆分字符串数组
按指定分隔符数组拆分字符串数组实现方案
实现思路
- 先将分隔符数组转为
HashSet<string>类型,避免遍历判断时的重复检索,提升执行效率 - 定义
List<List<string>>类型的临时结果容器,以及List<string>类型的当前分片临时容器 - 遍历原数组所有元素:
- 若当前元素属于分隔符集合:
- 若当前分片临时容器不为空,将其转为数组后加入结果容器
- 清空当前分片临时容器,将当前分隔符元素加入作为新分片的首元素
- 若当前元素不属于分隔符集合,直接加入当前分片临时容器
- 若当前元素属于分隔符集合:
- 遍历结束后,将最后剩余的当前分片临时容器内容转为数组加入结果容器
- 最后可根据需求将结果容器转为
string[][]或者保留List<string[]>类型
如果你不想引入HashSet,也可以用
Array.IndexOf(separators, item) > -1来判断当前元素是否为分隔符,效果一致,只是数据量较大时效率略低于HashSet方案,同时也呼应了提示中的IndexOf()用法。
完整实现代码
using System; using System.Collections.Generic; using System.Linq; public class ArraySplitter { public static List<string[]> SplitArrayBySeparators(string[] sourceArray, string[] separators) { var separatorSet = new HashSet<string>(separators); var result = new List<string[]>(); var currentSegment = new List<string>(); foreach (var item in sourceArray) { if (separatorSet.Contains(item)) { if (currentSegment.Count > 0) { result.Add(currentSegment.ToArray()); } currentSegment.Clear(); currentSegment.Add(item); } else { currentSegment.Add(item); } } // 加入最后一个分片 if (currentSegment.Count > 0) { result.Add(currentSegment.ToArray()); } return result; } // 测试用例 public static void Main() { string[] array1 = { "item1", "item2", "item3", "item4", "item5" ,"item6" }; string[] array2 = { "item2", "item5" }; var results = SplitArrayBySeparators(array1, array2); // 输出验证结果 for (int i = 0; i < results.Count; i++) { Console.WriteLine($"results[{i}] = {{ \"{string.Join("\", \"", results[i])}\" }}"); } } }
输出结果
运行测试用例后输出内容和预期完全一致:
results[0] = { "item1" } results[1] = { "item2", "item3", "item4" } results[2] = { "item5", "item6" }
内容的提问来源于stack exchange,提问作者Honey22Sharp
相关产品推荐
相关产品推荐

