VB
Microsoft 开发的一种面向对象的编程语言,其在 .NET Framework 上实现。 以前称为 Visual Basic .NET。
78 个问题
你好
我正在尝试对包含空格的字符串进行排序。例如,字符串:“Hello World”将为“dehll loorw”。目前,当我对字符串进行排序时,空格放置在字符串的末尾,但我需要它保持在同一个位置。
谢谢。
Note:此问题总结整理于:How to sort a string, but keep spaces in the same place
您需要记录每个空格的索引并在排序后插入。 下面是一个可以参考的示例。
Private Function SortStringToLower(ByVal input As String) As String
Dim indexLst As List(Of Integer) = New List(Of Integer)
Dim pos As Integer = input.IndexOf(" "c)
While pos >= 0
indexLst.Add(pos)
pos = input.IndexOf(" "c, pos + 1)
End While
Dim characters As Char() = input.ToLower.Replace(" ", "").ToArray()
Array.Sort(characters)
Dim builder As StringBuilder = New StringBuilder(New String(characters))
For Each index In indexLst
builder.Insert(index, " "c)
Next
Return builder.ToString
End Function
Sub Main()
Dim str As String = "H ello Worl d"
Dim result As String = SortStringToLower(str)
Console.WriteLine(result)
Console.ReadLine()
End Sub
结果:
如果答案有帮助,请点击“接受答案”并点赞。
注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。