如何按指定长度拆分字符串?解决代码丢失末尾短片段问题
修复字符串拆分方法以保留末尾片段
当前代码存在两个核心问题:
- 使用
str.Length / size做整数除法会直接截断余数,导致最后一段不足指定长度的片段被忽略; - 固定调用
Substring(i * size, size)会在剩余字符不足时抛出参数越界异常。
修改后的代码(LINQ 版本)
private IEnumerable<string> SplitString(string str, int size) { if (size <= 0) throw new ArgumentOutOfRangeException(nameof(size), "拆分长度必须大于0"); // 用 (长度 + 大小 -1)/大小 实现整数除法向上取整,计算总块数 int totalChunks = (str.Length + size - 1) / size; return Enumerable.Range(0, totalChunks) .Select(i => str.Substring(i * size, Math.Min(size, str.Length - i * size))); }
修改后的代码(循环版本,可读性更高)
private IEnumerable<string> SplitString(string str, int size) { if (size <= 0) throw new ArgumentOutOfRangeException(nameof(size), "拆分长度必须大于0"); int currentIndex = 0; while (currentIndex < str.Length) { // 取剩余字符数与指定长度的较小值,避免越界 int chunkLength = Math.Min(size, str.Length - currentIndex); yield return str.Substring(currentIndex, chunkLength); currentIndex += chunkLength; } }
效果说明
两种版本都会完整保留所有片段:以输入字符串长度17、拆分长度7为例,会生成3个片段——前两个各7字符,最后一个3字符,完全符合期望结果。同时添加了参数合法性校验,避免无效输入导致的错误。
内容的提问来源于stack exchange,提问作者Ullan
相关产品推荐
相关产品推荐

