How do you sort words in a string?
If you have this text:
this text needs to be sorted
Then when it is sorted it would turn into:
be needs sorted text this to
Printable View
How do you sort words in a string?
If you have this text:
this text needs to be sorted
Then when it is sorted it would turn into:
be needs sorted text this to
I would put the text into a stringreader, then do a SPLIT and SPLIT at each space and insert the items into an array and sort.
Wrox VB.net text manipulation handbook is a WONDERFUL book..
Is that the easiest way to do this?
Hmm I don't this it's that involved.
The following is a snippet from WROX VB.net Text Manipulation Handbook.. This is to split
Dim inputstring as string = "123,abc,456,def"
dim splitresults as string
dim string element as string
splitresults = regex.splut(inputstring, ",")
for each stringelement in splitresults
results += stringelement & controlchars.crlf
next
Then inside the for each loop you throw it into the array. once in the array then parse the array and then put it back together. Do yourself a HGUE favor and get this book. I recommend it to EVERYONE that needs to manipulate text in vb.net
Just pass in a string to the SortString method, and you will get a string in return that is sorted. It won't account for every possiblity, but if you have a string of words that is seperated by spaces, it will work just fine.
VB Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click MessageBox.Show(SortString("This is the new string to sort")) End Sub Private Function SortString(ByVal theString As String) As String Dim arrayOfStrings() As String = theString.Split(" ") Array.Sort(arrayOfStrings) Dim mystrBuilder As System.Text.StringBuilder = New System.Text.StringBuilder() Dim i As Integer For i = 1 To arrayOfStrings.GetUpperBound(0) - 1 mystrBuilder.Append(arrayOfStrings(i) & " ") Next Dim returnString As String = mystrBuilder.ToString() returnString = returnString.Trim() Return returnString End Function
very nice!
Thanks, I bet there is even better ways to modify it though to make it more efficient. I just threw it together as an example.
Thanks but I dosn't seem to work properly.
If I have this string:
This is the new string to sort
then I end up with this string:
new sort string the This
It's missing two words; is and to.
this:
should have been:VB Code:
For i = 1 To arrayOfStrings.GetUpperBound(0) - 1 mystrBuilder.Append(arrayOfStrings(i) & " ") Next
VB Code:
For i = 0 To arrayOfStrings.GetUpperBound(0) mystrBuilder.Append(arrayOfStrings(i) & " ") Next
duh...lol... that is what I get for hurrying. Thanks for the catch on that one. I don't use VB.Net much, I was thinking it was different than C# in how it dealt with indexes of arrays.
C# arrays are 1-based?
No, but I thought VB.Net ones were for some reason when I was writing that. Although, I made the mistake on both ends....lol.
It's working good now :)
Thanks for all the help!