How to sort a string, but keep spaces in the same place

JasonDaurison 116 Reputation points
2021-05-26T01:34:26.027+00:00

Hello,

I am trying to sort a string that has spaces in it. For example the string: "Hello World", would be "dehll loorw". Currently when I sort the string the space is placed at the end of the string, but I need it to stay in the same place.

Thanks.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,614 questions
{count} votes

Accepted answer
  1. Xingyu Zhao-MSFT 5,356 Reputation points
    2021-05-26T07:38:24.533+00:00

    Hi @JasonDaurison ,
    You need to record the index of each space and insert them after sorting.
    Here's an example you can refer to.

        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  
    

    Result:
    99773-1.png

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful