How to get a sub-string array from array string c# -
i'm new c#.
have string split string array , 1 of elements needs split again string array parsed differently. i'm trying convert string arrays float arrays , combine them 1 final float array @ original position.
string ido = "433, 045, 3-3-15, 444, 0.6,3.9,4,5,5,4,3,3"; string[] sn= ido.split(',', 13, stringsplitoptions.removeemptyentries); string subnum = sn[2]; string[] st = subnum.split('-',3,stringsplitoptions.removeemptyentries); float [] stnum = array.convertall<string, float>(st, float.parse) float[] farray = new float[ float.parse(sn[0]), float.parse(sn[1]),... stnum, float.parse(sn[3:end])];
i know last line wrong. don't want feed each element float.parse() individually. i'm trying there better way this? can use convertall how elements in string array element 3 end of array?
since want result of array of floats, can split original string on both ','
, '-'
characters, end array of "number strings". can use float.tryparse()
convert each "number string" float
, add them array.
private static void main() { string ido = "433, 045, 3-3-15, 444, 0.6,3.9,4,5,5,4,3,3"; // split on both comma , dash var items = ido.split(',', '-'); // list hold items converted floats var result = new list<float>(); foreach (var item in items) { float temp; // use tryparse ensure can convert each item if (float.tryparse(item, out temp)) { result.add(temp); } } // display final results console.writeline(string.join(", ", result)); }
ouput:
433, 45, 3, 3, 15, 444, 0.6, 3.9, 4, 5, 5, 4, 3, 3
note in example above used list<float>
because if tryparse
fails item in original array, won't add item final result , therefore don't know how many items initialize array with. if really need array, can convert list array calling toarray()
method so:
float[] arrayresult = result.toarray();
update
you can shorten whole thing down couple of lines if you're familiar linq:
string ido = "433, 045, 3-3-15, 444, 0.6,3.9,4,5,5,4,3,3"; float temp = 0; // temporarily holds each converted item float[] arrayresult = ido.split(',', '-') .where(item => float.tryparse(item, out temp)) .select(item => temp) .toarray();