Split String by number of characters

G

Guest

Hi,

I want to split a big string by nymber of characters. for eg., if total
length of the string is 80 and I want to split by each 10 characters and get
8 lines of output.

I written a function but still I search for the optimized one because the
strings I receive will be long. Is there are any special classes or I can use
regular expressions?

Please help.

TIA,
Holy
 
J

Jon Shemitz

I want to split a big string by nymber of characters. for eg., if total
length of the string is 80 and I want to split by each 10 characters and get
8 lines of output.

I written a function but still I search for the optimized one because the
strings I receive will be long. Is there are any special classes or I can use
regular expressions?

I don't believe there are any classes designed specifically for this.
Just don't code the function as

while (Input != "")
{
int ThisLength = Math.Max(TargetLength, Input.Length);
Output.Add(Input.Substring(0, ThisLength));
Input = Input.Remove(0, ThisLength);
// all this 'popping' is VERY expensive on big strings
}

instead, move a LeftPtr along, and Substring() from that.

Alternatively, you could construct a regex

string Pattern = String.Format(".{1,{{0}}}", TargetLength)
// or
string Pattern = ".{1," + TargetLength.ToString() + "}";

// in either case, be sure to use RegexOptions.Singleline

and construct your output from the Matches collection (or by calling
Match / NextMatch). Might be a bit less code than the LeftPtr
alternative, and probably about as performant.
 
J

Jay B. Harlow [MVP - Outlook]

Holysmoke,
As Jon suggests there are no built-in functions per se.

I would consider using a For loop & String.SubString (variation of Jon's
LeftPtr), something like:

Dim length As Integer = 4
Dim input As String = "123456789012"

Dim lines((input.Length \ length) - 1) As String

For index As Integer = 0 To lines.Length - 1
lines(index) = input.Substring(index * length, length)
Next

NOTE: This function assumes that the String.Length is a multiple of the
length parameter, any extra is ignored...

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top