2011-06-27 82 views
2

我有一個這樣的字符串:如何重新排列字符串中的字符?

1a2b3c4d5e6f7g8h 

,我需要重新安排它如下:

a1b2c3d4e5f6g7h8 

你明白我的意思嗎?對於每兩個字符,數字字符交換的地方有以下字母,即從1a改變它a1

所以我的問題是如何重新排列數字字符和字母串嗎?我的字符串總是有上述模式,即一個整數,然後是一個字母,然後是一個整數,然後是一個字母,依此類推。

回答

3

我覺得這樣的事情應該做你想要什麼:

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) 
4

你可以用簡單的regex更換做到這一點。

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

輸出:

1a2b3c4d5e6f7g8h --> a1b2c3d4e5f6g7h8