开发者

How to rearrange characters in a string?

I have a string like this:

1a2b3c4d5e6f7g8h

And I need to rearrange it as follow:

a1b2c3d4e5f6g7h8

Do you understand what I mean? For each two characters, the numerical character swapping place with the following letter, i.e. from 1a change it to a1

So my question is how to rearrange the numerical characters a开发者_如何学Gond letters in the string? My string always has the said pattern, i.e. one integer then followed by a letter then followed by a integer then followed by a letter and so on.


You can do this with simple regex replacement.

Dim input As String = "1a2b3c4d5e6f7g8h"
Dim output As String = Regex.Replace(a, "(\d)(\w)", "$2$1")
Console.WriteLine(input & " --> " & output)

Output:

1a2b3c4d5e6f7g8h --> a1b2c3d4e5f6g7h8


I think something like this should do what you want:

    Dim input As String
    input = "1a2b3c4d5e6f7g8h"

    Dim tmp As Char()
    tmp = input.ToCharArray()

    For index = 0 To tmp.Length - 2 Step 2
        Dim a As Char
        a = tmp(index + 1)
        tmp(index + 1) = tmp(index)
        tmp(index) = a
    Next

    Dim output As String
    output = New String(tmp)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜