C#删除字符串空格后按固定长度拆分报错 如何优化代码实现
报错原因分析
- 循环边界错误:你使用了
i <= str.Length作为循环条件,而字符串的有效索引范围是0 到 str.Length - 1,以你报错时的场景为例,处理后的字符串长度为12,当i自增到12时,已经超出了字符串的最大有效索引11,此时调用Substring自然触发索引越界错误。 - 剩余字符长度未兼容:就算修正循环边界为
i < str.Length,如果字符串总长度不是拆分长度的整数倍,最后一轮循环时剩余的字符数会小于size,你直接传入size作为截取长度,同样会触发越界错误。
重构实现方案
基础修复版本
完全匹配你的原有需求,修复报错问题,同时简化冗余代码:
public string Reshape() { string str = "1254k 698 7785"; // 移除所有空格 str = str.Replace(" ", ""); int size = 3; List<string> listFormat = new List<string>(); for (int i = 0; i < str.Length; i += size) { // 动态计算实际截取长度,剩余字符不足时取剩下的所有字符 int actualSplitLength = Math.Min(size, str.Length - i); listFormat.Add(str.Substring(i, actualSplitLength)); } // 不需要额外调用ToArray,string.Join原生支持IEnumerable<string>类型参数 return string.Join(Environment.NewLine, listFormat); }
通用优化版本
如果需要复用该能力,可以封装为通用扩展方法,同时优化性能:
public static class StringProcessExtensions { /// <summary> /// 重塑字符串格式:可选移除空格后按指定长度拆分换行 /// </summary> /// <param name="input">原始输入字符串</param> /// <param name="splitSize">每行拆分长度</param> /// <param name="removeAllWhitespace">是否移除所有空格</param> /// <returns>拆分后的结果字符串</returns> /// <exception cref="ArgumentOutOfRangeException">拆分长度小于等于0时抛出</exception> public static string Reshape(this string input, int splitSize, bool removeAllWhitespace = true) { if (string.IsNullOrEmpty(input)) return string.Empty; if (splitSize <= 0) throw new ArgumentOutOfRangeException(nameof(splitSize), "拆分长度必须大于0"); string processedStr = removeAllWhitespace ? input.Replace(" ", "") : input; // 提前指定List容量,避免动态扩容损耗 List<string> splitParts = new List<string>((int)Math.Ceiling((double)processedStr.Length / splitSize)); for (int i = 0; i < processedStr.Length; i += splitSize) { int actualLength = Math.Min(splitSize, processedStr.Length - i); splitParts.Add(processedStr.Substring(i, actualLength)); } return string.Join(Environment.NewLine, splitParts); } } // 调用示例 // string result = "1254k 698 77".Reshape(3);
内容的提问来源于stack exchange,提问作者Coder-Meca
相关产品推荐
相关产品推荐

