在VB.NET中每2个字符添加空格

时间:2017-08-22 10:06:10

标签: string vb.net char

美好的一天,专家。我从uart得到16个字符串值,就像这个“0000000000001110”,然后我想每2个字符添加空格:“00 00 00 00 00 00 11 10”。我在想什么是在“数据”中每2个字符进行下一次循环计数,然后在它之间添加一个空格。但我真的不知道如何实现它。这就是我到目前为止所做的:

Dim i As Long
Dim data As String = "0000000000001110"

For i = 0 To Len(data) Step 2 ' counting every 2 chars
    data = Mid(data, i + 1, 2)  ' assign 2 chars to data 
   ' stucked here
Next i

感谢任何意见,谢谢。

4 个答案:

答案 0 :(得分:1)

您可以使用StringBuilder和向后循环:

Dim data As String = "0000000000001110"
Dim builder As New StringBuilder(data)
Dim startIndex = builder.Length - (builder.Length Mod 2)

For i As int32 = startIndex to 2 Step -2
   builder.Insert(i, " "c)
Next i
data = builder.ToString()

使用If的条件运算符(在VB Mod中)用于查找起始索引(从字符串末尾开始)。因为如果字符串具有偶数/奇数个字符,它将是不同的。我使用向后循环来防止插入字符会改变字符串/ StringBuilder大小的问题,从而在for循环中导致错误的索引。

这是一种扩展方法,它封装了复杂性并提高了可重用性:

Imports System.Runtime.CompilerServices
Imports System.Text

Module StringExtensions
    <Extension()> 
    Public Function InsertEveryNthChar(str As String, inserString As String, nthChar As Int32) As String
        If string.IsNullOrEmpty(str) then Return str

        Dim builder as New StringBuilder(str)
        Dim startIndex = builder.Length - (builder.Length Mod nthChar)

        For i As int32 = startIndex to nthChar Step -nthChar
            builder.Insert(i, inserString)
        Next i

        return builder.ToString()
    End Function
End Module

用法:

Dim data = "00000000000011101"
data = data.InsertEveryNthChar("[foo]", 3) ' 000[foo]000[foo]000[foo]000[foo]111[foo]01

答案 1 :(得分:0)

我知道您已经接受了答案,但是您也可以像这样执行所需的任务。
确保导入System.Text以便您可以使用StringBuilder

输出:00 00 00 00 00 00 11 10

Dim data As String = "0000000000001110"
    Dim sb As New StringBuilder()
    Dim addSpace As Boolean = False
    For Each c As Char In data
        If addSpaceThen
            sb.Append(c + " ")
            addSpace = False
        Else
            sb.Append(c)
            addSpace = True
        End If
    Next
    sb.Length = sb.Length - 1 ''Remove last space on string
    Console.WriteLine(sb.ToString())

答案 2 :(得分:0)

如果你是NuGet&#34; System.Interactive&#34;你为Buffer添加了一个非常整洁的IEnumerable(Of T)运算符。然后这工作:

Dim data As String = "0000000000001110"
Dim result = String.Join(" ", data.Buffer(2).Select(Function (x) New String(x.ToArray())))

如果你想直接使用LINQ,那么这可行:

Dim result = String.Join(" ", data.Select(Function (x, n) New With { x, n }).GroupBy(Function (x) x.n \ 2, Function (x) x.x).Select(Function (y) New String(y.ToArray())))

答案 3 :(得分:0)

'这是最简单的外行级别的解决方案

Dim i As Long  
        Dim A, b, C As String  
        A = Mid(mac, i + 1, 2) 'assign the first 2 value to the variable  
        C = A 'transfer it to main section  
        For i = 0 To Len(mac) - 4 Step 2  ' counting every 2 chars and looping should be 4 characters less.  
            b = Mid(mac, i + 3, 2)   ' assign 2 chars to data  
            b = "-" + b'put the dashes in front of every other character  
            C = C + b  
    Next i