2015-09-05 104 views
1

我使用的是C#.NET應用程序,但我想把它移植到C#控制檯應用程序遷移到控制檯應用程序和用戶輸入

類:

static class StringExtensions 
{ 
    public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) 
    { 
     if (s == null) 
      throw new ArgumentNullException("s"); 
     if (partLength <= 0) 
      throw new ArgumentException("Part length has to be positive.", "partLength"); 

     for (var i = 0; i < s.Length; i += partLength) 
      yield return s.Substring(i, Math.Min(partLength, s.Length - i)); 
     } 

} 

電話:

var parts = "32427237".SplitInParts(3); 
Console.WriteLine(String.Join(" ", parts)); 

//輸出是324 272 37

所以我想給用戶輸入數值,例如123456789和split outpu t是123 456 789,我該如何在控制檯應用程序上做到這一點?

------------------------------ UPDATE --------------- ---------------------------

完整代碼:

namespace prw 
{ 
    class Program 
    { 
     public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) 
     { 
      if (s == null) 
       throw new ArgumentNullException("s"); 
      if (partLength <= 0) 
       throw new ArgumentException("Part length has to be positive.", "partLength"); 

      for (var i = 0; i < s.Length; i += partLength) 
       yield return s.Substring(i, Math.Min(partLength, s.Length - i)); 
     } 




     private static void Main(string[] args) 
     { 
      var input= Console.ReadLine(); 
      var parts = input.SplitInParts(3); 
      Console.WriteLine(String.Join(" ", parts)); 
     } 
    } 
} 
+1

使用到Console.ReadLine()! – Arash

+0

但如果我想創建新的控制檯proyect,只需複製我的代碼並更改讀線的writeline? –

回答

1
class Program 
{ 
    private static void Main(string[] args) 
    { 
     var input= Console.ReadLine(); 
     var parts = input.SplitInParts(3); 
     Console.WriteLine(String.Join(" ", parts)); 
    } 
} 
public static class Util 
{ 
    public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) 
    { 
     if (s == null) 
      throw new ArgumentNullException("s"); 
     if (partLength <= 0) 
      throw new ArgumentException("Part length has to be positive.", "partLength"); 

     for (var i = 0; i < s.Length; i += partLength) 
      yield return s.Substring(i, Math.Min(partLength, s.Length - i)); 
    } 
} 
+0

我有一個代碼錯誤...當我聲明這個字符串s時,它說擴展方法只能在非泛型,非嵌套靜態類中聲明。我上傳我的代碼 –

+1

@Gerardo Ventas我改變了代碼 – Arash

+0

優秀,坦克你這麼多! @Arash jo –

相關問題