1

I have string contains three numbers which seperated by comma or by space.

For example: "3,3,3" or "3 3 3".

The string can contains also spaces between the numbers or at the start\end of the string.

I want to insert them into array.

I did:

this.ang[0] = Convert.ToDouble(ang.Trim().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)[0]);
this.ang[1] = Convert.ToDouble(ang.Trim().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)[1]);
this.ang[2] = Convert.ToDouble(ang.Trim().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)[2]);

How can I insert the data into the array with less code lines?

Thanks!

reza.cse08
  • 5,938
  • 48
  • 39
Programmer
  • 371
  • 1
  • 8
  • 21

4 Answers4

1

You try using Linq:

 String ang = "3,3,3"; 

 double[] result = ang
   .Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
   .Select(item => Convert.ToDouble(item))
   .ToArray();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

The String.Split() method already returns an array, so you could perform your split and use LINQ's Select() method to to parse each value as a double and store these values in an array :

// This will store the double value for each of your elements into an array
this.ang = ang.Trim().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
                     .Select(x => Convert.ToDouble(x))
                     .ToArray();

If you can't explicitly set your this.ang array, then you could store the previous result in a variable and use it to set the individual values as necessary.

Example

You can see a working example of this in action here.

Rion Williams
  • 74,820
  • 37
  • 200
  • 327
0

The already suggested answers suppose that you can re-assign the entire array ang. If you can't, you have to pass through a for iteration:

var splitString = ang
    .Trim()
    .Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)

for(int i = 0; i < 3; i++)
{
    this.ang[i] = Convert.ToDouble(splitString[i]);
}
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
0
var ang = "3,3,3"; // or "3 3 3";
var res = ang.Trim().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(x => Convert.ToDouble(x))
                    .ToList();
Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74
reza.cse08
  • 5,938
  • 48
  • 39