Reputation: 370
The following is a piece of code I have written
string arrayToConvert = "$78 89 12 78 89 12%";
string s2 = s1.Substring(1, s1.Length - (2));
There are 2 objectives to be achieved
I am able to remove the first and last character in a string and store it into a new one, no problem. The trouble is when I try to put the data into integer array. I tried using the following syntax to achieve the desired goal.
int[] ia = s1.Split(' ').Select(int.Parse).ToArray();
and
int n;
int[] ia = s1.Split(' ').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();
The output obtained is "4455667788110121" which clearly are not the numbers in the input string. If this question is a duplicate, kindly point me in the right direction. Any help appreciated.
Upvotes: 0
Views: 700
Reputation: 131189
Most likely you are using the wrong strings. Your original string is `arrayToConvert yet you try to clean up some other string, s1. Finally you try to split s1, not the cleaned up s2.
The following line returns an array with the expected values:
var ints= "$78 89 12 78 89 12%"
.Trim(new[]{'$','%'})
.Split(' ')
.Select(int.Parse)
.ToArray();
I used Trim
rather than Substring
simply to put everything in a single statement.
Upvotes: 1