Sunday, 15 September 2013

c# - Split string after specific character or after max length -



c# - Split string after specific character or after max length -

i want split string next way:

string s = "012345678x0123x01234567890123456789"; s.splitstring("x",10);

should split into

012345678 x0123 x012345678 9012345678 9

e.g. inputstring should split after character "x" or length 10 - comes first.

here i've tried far:

public static ienumerable<string> splitstring(this string sinput, string search, int maxlength) { int index = math.min(sinput.indexof(search), maxlength); int start = 0; while (index != -1) { yield homecoming sinput.substring(start, index-start); start = index; index = math.min(sinput.indexof(search,start), maxlength); } }

personally don't regex. creates code hard de-bug , hard work out meant doing when first @ it. more lengthy solution go this.

public static ienumerable<string> splitstring(this string sinput, char search, int maxlength) { var result = new list<string>(); var count = 0; var lastsplit = 0; foreach (char c in sinput) { if (c == search || count - lastsplit == maxlength) { result.add(sinput.substring(lastsplit, count - lastsplit)); lastsplit = count; } count ++; } result.add(sinput.substring(lastsplit, count - lastsplit)); homecoming result; }

note changed first parameter char (from string). code can optimised more, nice , readable, me more important.

c# string split

No comments:

Post a Comment