如何按字符特征拆分字符串?实现括号内外元素的正确分割
问题:拆分带括号的字符串为指定格式数组
需求:将给定字符串转换为string类型数组,要求()内的字符作为一个元素,括号外的每个单独字符各作为一个元素。
示例:
输入字符串:
string test = "(af)sd(abc)abc"
期望生成数组:
string[] testSplitted = { "af", "s", "d", "abc", "a", "b", "c" };
当前代码仅能将括号内的内容作为数组元素,括号外的字符会被合并,得到错误结果:
string[] testSplitted = { "af", "sd", "abc", "abc" };
现有代码如下:
public static string[] transmissions = { "(ab)(bc)(ca)", "abc", "(abc)(abc)(abc)", "(zyx)bc" }; public static string[] words = { "abc", "bca", "dac", "dbc", "cba" }; public static void Main() { for (int y = 0; y < N; y++) { string[] charSplit = transmissions[y].Replace("(", "").Replace(")", "").Split(); int K = 0; foreach (var item in words) { int matches = 0; for (int i = 0; i < item.Length; i++) { if (!charSplit[i].Contains(item[i])) { break; } matches++; } if (matches == 3) { K++; } } Console.WriteLine("Case #" + (y + 1) + ": " + K); } }
解决方案
可以通过遍历字符串,手动处理括号内和括号外的内容来实现需求,替换原有的charSplit生成逻辑:
public static string[] transmissions = { "(ab)(bc)(ca)", "abc", "(abc)(abc)(abc)", "(zyx)bc" }; public static string[] words = { "abc", "bca", "dac", "dbc", "cba" }; public static void Main() { for (int y = 0; y < transmissions.Length; y++) { string input = transmissions[y]; List<string> charSplit = new List<string>(); int i = 0; while (i < input.Length) { if (input[i] == '(') { // 找到对应的右括号位置 int closeIndex = input.IndexOf(')', i); if (closeIndex != -1) { // 提取括号内的内容加入列表 charSplit.Add(input.Substring(i + 1, closeIndex - i - 1)); i = closeIndex + 1; } else { // 处理无匹配右括号的情况,按单个字符处理 charSplit.Add(input[i].ToString()); i++; } } else { // 括号外的单个字符直接加入列表 charSplit.Add(input[i].ToString()); i++; } } int K = 0; foreach (var item in words) { int matches = 0; for (int j = 0; j < item.Length; j++) { // 增加数组越界判断,避免报错 if (j >= charSplit.Count || !charSplit[j].Contains(item[j])) { break; } matches++; } if (matches == 3) { K++; } } Console.WriteLine("Case #" + (y + 1) + ": " + K); } }
关键修改点说明:
- 替换原有的
Replace+Split逻辑,改为手动遍历字符串:- 遇到
(时,找到对应的),提取中间内容作为一个元素; - 非括号字符直接以单个字符作为元素;
- 遇到
- 修复原代码中未定义的
N变量,替换为transmissions.Length; - 在匹配逻辑中增加
j >= charSplit.Count的判断,避免数组越界。
内容的提问来源于stack exchange,提问作者lurkagurka
相关产品推荐
相关产品推荐

