Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

.net - How to split a string into a fixed length string array?

I have a long string like this

dim LongString as String = "123abc456def789ghi"

And I want to split it into a string array. Each element of the array should be in 3 characters length

For example,

Dim LongArray(5) As String
LongArray(0)  = "123"
LongArray(1)  = "abc"
LongArray(2)  = "456"
LongArray(3)  = "def"
LongArray(4)  = "789"
LongArray(5)  = "ghi"

How do I split it using VB.net code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use LINQ like so:


' VB.NET
Dim str = "123abc456def789ghij"
Dim len = 3
Dim arr = Enumerable.Range(0, str.Length / len).Select (Function(x) str.Substring(x * len, len)).ToArray()


// C#
var str = "123abc456def789ghij";
var len = 3;
var arr = Enumerable.Range(0, str.Length / len).Select (x => str.Substring(x * len, len)).ToArray();

Note this will only take complete occurrences of length (i.e. 3 sets in a string 10 characters long).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...