Alex Rivera | Logout

Splitting strings at specific positions

Asked 2011-05-31T09:22:14.233
9

I got a little problem here, i'm looking for a better way to split Strings. For example i receive a String looking like this.

0000JHASDF+4429901234ALEXANDER

I know the pattern the string is built with and i have an array of numbers like this.

4,5,4,7,9
0000 - JHASDF - +442 - 9901234 - ALEXANDER

It is easy to split the whole thing up with the String MID command but it seems to be slow when i receive a file containing 8000 - 10000 datasets. So any suggestion how i can make this faster to get the data in a List or an Array of Strings? If anyone knows how to do this for example with RegEx.

Edit
Report

1 Answer

3

Perhaps something like this:

string[] SplitString(string s,int[] parts)
{
  string[] result=new string[parts.Length];
  int start=0;
  for(int i=0;i<parts.Length;i++)
  {
    int len=parts[i];
    result[i]=s.SubString(start, len);
    start += len;
  }
  if(start!=s.Length)
    throw new ArgumentException("String length doesn't match sum of part lengths");
  return result;
}

(I didn't compile it, so it probably contains some minor errors)

answered 2011-05-31T09:27:26.207

Your Answer