-3

I am kinda stuck at the moment, i have a string of numbers which i dynamically get them from database, the range of numbers can be between 1 to 1 milion, something like this :

string str = "10000,68866225,77885525,3,787";

i need to create an array from it, i have tried this:

string[] strArr = { str.Replace(",", "").Split(',') };

but it doesnt work anyone has any solution i am all ours. Basically it needs to be like this:

string[] strArr = { "10000","68866225","77885525","3","787" };
SmackDat
  • 183
  • 1
  • 4
  • 15

5 Answers5

1

Your attend:

string[] strArr = { str.Replace(",", "").Split(',') };

does not work because of two errors in the code:

1) You are removing all , before you are splitting at ,:

str.Replace(",", "")

So basically you are trying to split this string: "1000068866225778855253787" at each ,, which will result in an array containing only "1000068866225778855253787" because obviously there is no , to split on.

2) You are trying to assign an array to a string, because the Split() method already returns an array and you are trying to put this array into a field of string[] (because of the { } around your assignment) and a field of string[] is of type string and not an array.


To get your expected output you have to do the .Split(',') on the original string, which includes all the , on which you are splitting. So just remove the Replace() call and you will get your desired output:

var str = "10000,68866225,77885525,3,787";
var strArr = str.Split(',');
croxy
  • 4,082
  • 9
  • 28
  • 46
0

Try this:

string[] strArr = str.Split(',');
Wudge
  • 357
  • 1
  • 6
  • 14
  • Hey thanks for answer, i was wondering what if i had one number returning? something like this - string str = "1"; does it return an array as well? – SmackDat Nov 16 '16 at 11:39
  • 1
    @SmackDat yes, you will have an array with only one element which is `"1"` – meJustAndrew Nov 16 '16 at 11:40
0

The split method already returns an array. Just take it out of the squiggly brackets.

string[] strArr = str.Split(',');

Edit: Sorry forgot to take out the .replace()

CrimsonSage
  • 217
  • 3
  • 12
0

The method string.Split() already returns an array.

0
string[] strArr =yourstring.Split(',');

This will return an array with possible split counts , for example "10000,68866225,77885525,3,787" will give array with the size of 4.

Venkat
  • 2,549
  • 2
  • 28
  • 61