0

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

  1. Removing the first and last character
  2. Transferring the string data into array of integers

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.

5
  • How do you output the int[]? Commented Jan 10, 2017 at 14:21
  • I can't reproduce this. The first snippet works "78 89 12 78 89 12".Split(' ').Select(int.Parse).ToArray() returns an array with 6 elements whose values are 78, 89, etc Commented Jan 10, 2017 at 14:22
  • Are you using the wrong strings perhaps? The original string is arrayToConvert yet you trim a different string, s1. Finally, you try to split that s1 string, not the trimmed one Commented Jan 10, 2017 at 14:24
  • Your string is arrayToConvert but you try to substring and split a string s1. Is this defined somewhere else in your code? Commented Jan 10, 2017 at 14:25
  • Yes, it was a synctactical error, thanks for pointing it out. The snippet does work. Commented Jan 10, 2017 at 15:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is by far the simplest solution I have come across yet. I appreciate the help, thank you.
Sir, conversely if I had to eliminate all special characters, alphabets and keep only the numbers is the string. For example "$67%!" or "$127a%". I am obtaining data from serial port and in certain cases there are alphabets/ special chars between $ and % or may be a number after %
@amatuer_programmer if you have another question, post it as a new question, not as a comment
Okay, fine, noted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.