求助:实现生成两个指定字符串间全序列的函数(附C#错误代码)
实现字符串间递增序列生成的C#方案
核心思路
把每个字符串看作由多组独立进制的字符组成(字母位为26进制,数字位为10进制),从起始字符串开始逐位递增,遇到边界(如字母Z、数字9)时触发进位逻辑,直到生成到结束字符串为止。
完整代码实现
using System; using System.Collections.Generic; public class StringSequenceGenerator { public static List<string> GenerateSequence(string start, string end) { List<string> result = new List<string>(); if (!ValidateInputs(start, end)) return result; char[] current = start.ToCharArray(); char[] endArr = end.ToCharArray(); do { result.Add(new string(current)); if (string.CompareOrdinal(new string(current), end) == 0) break; } while (TryIncrementString(ref current, endArr)); return result; } private static bool ValidateInputs(string start, string end) { if (start.Length != end.Length) return false; for (int i = 0; i < start.Length; i++) { char sChar = start[i]; char eChar = end[i]; bool sIsLetter = char.IsLetter(sChar); bool eIsLetter = char.IsLetter(eChar); // 对应位置字符类型必须一致 if (sIsLetter != eIsLetter) return false; // 起始串对应位置字符不能大于结束串 if (sIsLetter) { if (char.ToUpper(sChar) > char.ToUpper(eChar)) return false; } else { if (sChar > eChar) return false; } } // 整体起始串不能大于结束串 return string.CompareOrdinal(start, end) <= 0; } private static bool TryIncrementString(ref char[] current, char[] end) { int index = current.Length - 1; while (index >= 0) { char curr = current[index]; char endChar = end[index]; bool isLetter = char.IsLetter(curr); char nextChar; if (isLetter) { char upperCurr = char.ToUpper(curr); if (upperCurr == 'Z') { // 字母到Z,重置为对应大小写的A,并进位 nextChar = char.IsLower(curr) ? 'a' : 'A'; // 重置后若超过结束串对应位,无法继续递增 if (char.Compare(nextChar, endChar) > 0) return false; current[index] = nextChar; index--; } else { nextChar = (char)(curr + 1); // 若递增后超过结束串对应位,需进位 if (char.Compare(nextChar, endChar) > 0) { current[index] = char.IsLower(curr) ? 'a' : 'A'; index--; } else { current[index] = nextChar; return true; } } } else { if (curr == '9') { // 数字到9,重置为0,并进位 nextChar = '0'; if (nextChar > endChar) return false; current[index] = nextChar; index--; } else { nextChar = (char)(curr + 1); // 若递增后超过结束串对应位,需进位 if (nextChar > endChar) { current[index] = '0'; index--; } else { current[index] = nextChar; return true; } } } } // 所有位处理完毕后,检查是否未超过结束串 return string.CompareOrdinal(new string(current), new string(end)) <= 0; } }
代码关键说明
- 输入验证:确保两个字符串长度一致、对应位置字符类型(字母/数字)匹配,且结束串整体不小于起始串。
- 递增逻辑:
- 从最后一位开始尝试递增,若当前位达到类型边界(Z/9),则重置为该类型的起始字符(A/0),并向前一位进位。
- 若当前位递增后未超过结束串的对应位,则直接完成递增;若超过,则触发进位逻辑。
- 序列生成:循环调用递增方法,每次生成的字符串加入结果列表,直到生成到结束串为止。
使用示例
var sequence = StringSequenceGenerator.GenerateSequence("ABC01", "ADE05"); foreach (var str in sequence) { Console.WriteLine(str); }
该调用会生成从ABC01到ADE05的所有递增序列,包括ABC01→ABC02→…→ABC99→ABD00→…→ADE05的完整序列。
内容的提问来源于stack exchange,提问作者desimizaj
相关产品推荐
相关产品推荐

