2016-03-03 37 views
0

的名單我有我到控制檯上輸入上一行用空格以下號碼:C#轉換空間分隔的字節數組整數到整數

4 20 3 3 1 

我讀了這條線,並將其分配給一個字符串變量。使用ASCIIEncoding.ASCII.GetBytes()我將字符串轉換爲一個字節數組。

如何將字節數組拆分爲整數,方法是刪除空格並將整數添加到列表中?

例如,上述數字將被轉換爲列表[4, 20, 3, 3, 1]

+1

你不需要將字符串轉換中的字節數組。只需拆分字符串,並將每個單個子字符串添加到您的列表中,並進行轉換 – Steve

+0

我明白如何做到這一點。然而,部分任務是將輸入編碼爲ASCII字符,這意味着我必須將其作爲字節數組來使用。 – phosphenes

+1

對不起,我不明白。將NUMBERS(數字)編碼爲ASCII字符的目的是什麼? – Steve

回答

1

您可以在輸入字符串調用.Split(" "),你會得到你需要的字符串數組。

比你需要將它們轉換爲int。如果您確定您輸入進來的那個樣子,你可以使用LINQ:

string[] split = input.Split(" "); 
List<int> values = split.Select(x => int.Parse(x)).ToList(); 
+0

謝謝,但是,我需要一個字節數組,其中整數之間有空格。 – phosphenes

+0

當然像_1測試4的輸入不是數字6_會導致例外 – Steve

+0

@Steve:這就是爲什麼我寫了「如果您確定您的輸入是以這種方式出現的」,否則就需要使用「int.TryParse」。 – Edin

1

編輯:添加byte[]的溶液,作爲唯一的問題爭論

我不知道爲什麼你不能只是把你的字符串,並得到的東西做,但這裏是從ASCII符號字節數組的解決方案的字符串。 注意任何其他非數字或空格字符和int32溢出。

List<byte[]> splitResult = new List<byte[]>(); 
IEnumerable<byte> bytes = new byte[] { (byte)'1', (byte)'2', (byte)' ', (byte)'5', (byte)'4', (byte)' ', (byte)' ' }; // <- this should be your bytes 
while (bytes.Any()) 
{ 
    byte[] oneNumberBytes = bytes.SkipWhile(x => x == ' ').TakeWhile(x => x != ' ').ToArray(); 
    if(oneNumberBytes.Count() > 0) splitResult.Add(oneNumberBytes); 
    bytes = bytes.SkipWhile(x => x == ' ').SkipWhile(x => x != ' '); 
} 

var result = splitResult.Select(sr => sr.Aggregate(0, (seed, asciiDigit) => seed * 10 + asciiDigit - '0')).ToList(); 

如果能夠恢復初始的字符串:

使用string.Split方法。

Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToList(); 
1

使用LINQ:

static void Main(string[] args) 
{ 
    var input = Console.ReadLine(); 
    var integers = input.Split(new Char[] { ' ' }).Select(x => Convert.ToInt32(x)).ToList(); 
}