Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting strings at specific positions

Tags:

string

c#

.net

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.

like image 391
Lim Avatar asked May 31 '11 09:05

Lim


People also ask

How do I split a string into multiple parts?

You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.


1 Answers

var lengths = new[] { 4, 6, 4, 7, 9 };
var parts = new string[lengths.Length];

// if you're not using .NET4 or above then use ReadAllLines rather than ReadLines
foreach (string line in File.ReadLines("YourFile.txt"))
{
    int startPos = 0;
    for (int i = 0; i < lengths.Length; i++)
    {
        parts[i] = line.Substring(startPos, lengths[i]);
        startPos += lengths[i];
    }

    // do something with "parts" before moving on to the next line
}
like image 64
LukeH Avatar answered Oct 31 '22 02:10

LukeH