Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String into Array with No Delimiter

Tags:

c#

.net

vb.net

I have a string like s = "abcdefgh". I want to split it by number of characters like:

a(0)="ab"
a(1)="cd"
a(2)="ef"
a(3)="gh"

Can someone tell me how to do this?

like image 273
Elmo Avatar asked Nov 28 '25 04:11

Elmo


2 Answers

You can use a regular expression to split into two-character groups:

Dim parts = Regex.Matches(s, ".{2}").Cast(Of Match)().Select(Function(m) m.Value)

Demo: http://ideone.com/ZVL2a (C#)

like image 128
mellamokb Avatar answered Nov 30 '25 16:11

mellamokb


Here's a Linq method that doesn't require writing a loop:

    Const splitLength As Integer = 2
    Dim a = Enumerable.Range(0, s.Length \ splitLength).
        Select(Function(i) s.Substring(i * splitLength, splitLength))
like image 40
Antagony Avatar answered Nov 30 '25 16:11

Antagony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!