2017-05-31 181 views
0

我有一個多行文本框,其中包含由逗號分隔的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位數字。

任何人都可以指導我如何實現這一目標。 預先感謝您。

+4

解決這樣你的問題不是分裂,但輸入端的驗證? – Steve

+0

「用戶可能輸入錯誤的手機號碼」,但當然您的用戶將始終正確使用逗號?似乎你需要在進一步處理之前驗證你的輸入。 –

+1

*請勿*使用此類字段。如果有的話,用戶很難正確輸入數據。一個快速和骯髒的解決方案將是使用多行文本框。對於人來說,換行符遠比逗號好得多。更好的是,使用顯示所有項目的*可編輯組合框*。您可以單獨驗證修改的項目。您只需要一個「添加」按鈕來添加新項目。 –

回答

3

您可以使用該擴展方法來把它們放到MAX-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)); 
} 
0

您有幾種選擇,

  1. 把一些輸入數據中的一種掩碼可防止用戶輸入無效數據。在您的用戶界面中,您可以標記錯誤並提示用戶重新輸入正確的信息。如果你走這條路,那麼像這樣的string[] nums = numbers.Split(',');就可以。
  2. 或者,您可以使用regex.split或regex.match並匹配模式。這樣的事情應該工作,假設你的號碼是在一個字符串中帶有前導逗號或空格

    正則表達式regex = new Regex(「(\ s |,)\ d {10},)」;

    string [] nums = regex.Split(numbers);

0

這是可以用一個簡單的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)); 
    } 
} 
相關問題