Bud*_*Joe 38 .net c# string algorithm
我想用特定的长度变量分解String.
它需要进行边界检查,以便在字符串的最后一部分不长于或长于字符串时不爆炸.寻找最简洁(但可以理解)的版本.
例:
string x = "AAABBBCC";
string[] arr = x.SplitByLength(3);
// arr[0] -> "AAA";
// arr[1] -> "BBB";
// arr[2] -> "CC"
Run Code Online (Sandbox Code Playgroud)
SLa*_*aks 64
你需要使用一个循环:
public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
for (int index = 0; index < str.Length; index += maxLength) {
yield return str.Substring(index, Math.Min(maxLength, str.Length - index));
}
}
Run Code Online (Sandbox Code Playgroud)
替代方案:
public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
int index = 0;
while(true) {
if (index + maxLength >= str.Length) {
yield return str.Substring(index);
yield break;
}
yield return str.Substring(index, maxLength);
index += maxLength;
}
}
Run Code Online (Sandbox Code Playgroud)
2 次选择:(对于那些谁也受不了while(true))
public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
int index = 0;
while(index + maxLength < str.Length) {
yield return str.Substring(index, maxLength);
index += maxLength;
}
yield return str.Substring(index);
}
Run Code Online (Sandbox Code Playgroud)
Han*_*son 12
易于理解的版本:
string x = "AAABBBCC";
List<string> a = new List<string>();
for (int i = 0; i < x.Length; i += 3)
{
if((i + 3) < x.Length)
a.Add(x.Substring(i, 3));
else
a.Add(x.Substring(i));
}
Run Code Online (Sandbox Code Playgroud)
虽然最好3应该是一个很好的常量.
它不是特别简洁,但我可能会使用这样的扩展方法:
public static IEnumerable<string> SplitByLength(this string s, int length)
{
for (int i = 0; i < s.Length; i += length)
{
if (i + length <= s.Length)
{
yield return s.Substring(i, length);
}
else
{
yield return s.Substring(i);
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我返回一个IEnumerable<string>,而不是一个数组.如果要将结果转换为数组,请使用ToArray:
string[] arr = x.SplitByLength(3).ToArray();
Run Code Online (Sandbox Code Playgroud)
我的解决方案:
public static string[] SplitToChunks(this string source, int maxLength)
{
return source
.Where((x, i) => i % maxLength == 0)
.Select(
(x, i) => new string(source
.Skip(i * maxLength)
.Take(maxLength)
.ToArray()))
.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
我实际上宁愿使用List<string>而不是string[].
| 归档时间: |
|
| 查看次数: |
52784 次 |
| 最近记录: |