Splitting strings at specific positions?

Var lengths = new { 4, 6, 4, 7, 9 }; var parts = new List(lengths. Length); // if you're not using . NET4 then use ReadAllLines rather than ReadLines foreach (string line in File.

ReadLines("YourFile. Txt")) { int index = 0; foreach (int length in lengths) { parts. Add(line.

Substring(index, length)); index += length; } // do something with "parts" before clearing it ready for the next line parts.Clear(); }.

1 Just realised that this is pretty much the same as Fredrik's answer. Having said that, using Substring is faster and more obvious than using Skip/Take/ToArray. – LukeH May 31 at 9:45 Thanks, thats almost the same thing I got already, searching for something else, but if there is no better or faster way to do it, than I simply have to live with it.

– Lim May 31 at 9:49 @user777382: You might be able to get slightly faster with small tweaks and micro-optimisations, but I don't think you'll find much faster than this general approach. – LukeH May 31 at 9:51 -1 for unnecessary usage of List, because the array length is known beforehand – George Polevoy May 31 at 9:53 2 @George: And do you think that's going to even be noticeable here? I'd be amazed if you can show me a benchmark where the difference between array and list isn't buried by the file I/O.

– LukeH May 31 at 10:06.

Perhaps something like this: string SplitString(string s,int parts) { string result=new stringparts. Length; int start=0; for(int i=0;iSubString(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).

String firstPart = string. Substring(0, 4); string secondPart = string. Substring(4, 5); string thirdPart = string.

Substring(9, 4); //...

As the Mid() function is VB, you could simply try string. Substring(0, 4); and so on.

I know, still getting a little confused VB. Net / C# programming with one at work and one at home. :P – Lim May 31 at 9:43.

The Regex Split Method would be a possibility, but since you don't have a specific delimiter in the string then I doubt it will be of any use and unlikely to be any faster. String. Substring is also a possibility.

You use it like: var myFirstString = fullString. Substring(0, 4).

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions