拆分具有最大字符限制的字符串

我试图将一个字符串拆分成许多字符串(List),每个字符串都有一个最大字符数限制。 所以说如果我有一个500个字符的字符串,并且我希望每个字符串的最大值为75,则会有7个字符串,最后一个字符串不会有完整的75个字符串。

我已经尝试了一些我在stackoverflow上找到的例子,但他们“截断”了结果。 有任何想法吗?

你可以编写自己的扩展方法来做类似的事情

static class StringExtensions { public static IEnumerable SplitOnLength(this string input, int length) { int index = 0; while (index < input.Length) { if (index + length < input.Length) yield return input.Substring(index, length); else yield return input.Substring(index); index += length; } } } 

然后你就可以这样称呼它

 string temp = new string('@', 500); string[] array = temp.SplitOnLength(75).ToArray(); foreach (string x in array) Console.WriteLine(x); 

我将使用C#String.Substring方法使用循环来解决这个问题。

请注意,这不是确切的代码,但您明白了。

 var myString = "hello world"; List list = new List(); int maxSize while(index < myString.Length()) { if(index + maxSize > myString.Length()) { // handle last case list.Add(myString.Substring(index)); break; } else { list.Add(myString.Substring(index,maxSize)); index+= maxSize; } } 

当你说拆分时,你指的是拆分function吗? 如果没有,这样的东西将起作用:

 List list = new List(); string s = ""; int num = 75; while (s.Length > 0) { list.Add(s.Substring(0, num)); s = s.Remove(0, num); } 

我认为这比其他答案更清晰:

  public static IEnumerable SplitByLength(string s, int length) { while (s.Length > length) { yield return s.Substring(0, length); s = s.Substring(length); } if (s.Length > 0) yield return s; } 

我假设可能是一个分界符 – 就像空格字符。

搜索字符串(instr),直到找到分隔符的下一个位置。

如果那是<你的子串长度(75)然后附加到当前子串。

如果没有,请启动一个新的子字符串。

特殊情况 – 如果整个子字符串中没有分隔符 – 那么您需要定义发生的情况 – 比如添加’ – ‘然后继续。

  public static string SplitByLength(string s, int length) { ArrayList sArrReturn = new ArrayList(); String[] sArr = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string sconcat in sArr) { if (((String.Join(" ", sArrReturn.ToArray()).Length + sconcat.Length)+1) < length) sArrReturn.Add(sconcat); else break; } return String.Join(" ", sArrReturn.ToArray()); } public static string SplitByLengthOld(string s, int length) { try { string sret = string.Empty; String[] sArr = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string sconcat in sArr) { if ((sret.Length + sconcat.Length + 1) < length) sret = string.Format("{0}{1}{2}", sret, string.IsNullOrEmpty(sret) ? string.Empty : " ", sconcat); } return sret; } catch { return string.Empty; } }