我有一个多行文本框,其中包含用逗号分隔的10位移动号码。我需要实现字符串的组至少100个移动号码。
100个移动电话号码将总共用99个逗号分隔。我试图编写的代码是拆分包含逗号小于100的字符串。
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));
}
}通过使用上述代码,我可以实现100个数字,因为100个数字将具有10* 100 (用于移动号码)+99(用于逗号)文本长度。但是这里的问题是用户可能输入错误的移动号码,比如9位,甚至11位。
有人能指导我如何做到这一点吗?提前谢谢你。
发布于 2017-05-31 10:05:46
您可以使用此扩展方法将它们放入最大-100个数字组:
public static IEnumerable<string[]> SplitByLength(this string str, string[] splitBy, StringSplitOptions options, int maxLength = int.MaxValue)
{
var allTokens = str.Split(splitBy, options);
for (int index = 0; index < allTokens.Length; index += maxLength)
{
int length = Math.Min(maxLength, allTokens.Length - index);
string[] part = new string[length];
Array.Copy(allTokens, index, part, 0, length);
yield return part;
}
}示例:
string text = string.Join(",", Enumerable.Range(0, 1111).Select(i => "123456789"));
var phoneNumbersIn100Groups = text.SplitByLength(new[] { "," }, StringSplitOptions.None, 100);
foreach (string[] part in phoneNumbersIn100Groups)
{
Assert.IsTrue(part.Length <= 100);
Console.WriteLine(String.Join("|", part));
}发布于 2017-05-31 10:19:51
你有几个选择
string[] nums = numbers.Split(',');这样的东西就可以了。发布于 2017-05-31 11:16:47
这可以通过一个简单的Linq代码来解决。
public static IEnumerable<string> SplitByLength(this string input, int groupSize)
{
// First split the input to the comma.
// this will give us an array of all single numbers
string[] numbers = input.Split(',');
// Now loop over this array in groupSize blocks
for (int index = 0; index < numbers.Length; index+=groupSize)
{
// Skip numbers from the starting position and
// take the following groupSize numbers,
// join them in a string comma separated and return
yield return string.Join(",", numbers.Skip(index).Take(groupSize));
}
}https://stackoverflow.com/questions/44281542
复制相似问题