Dear all expert,
Please tell me how to sort string from "9874056213" to "0123456789".
Thank you for all post.
Printable View
Dear all expert,
Please tell me how to sort string from "9874056213" to "0123456789".
Thank you for all post.
Read each character and build a new string with the lowest character first etc. Use Mid$ and Instr in a loop to read the characters.
Code:Const TESTDATA = "9874056213"
Dim strNew As String
Dim lngIndex As Long
Dim lngIndexNew As Long
strNew = Mid$(TESTDATA, 1, 1)
lngIndex = 2
Do Until lngIndex = Len(TESTDATA) + 1
For lngIndexNew = 1 To Len(strNew)
If Mid$(TESTDATA, lngIndex, 1) < Mid$(strNew, lngIndexNew, 1) Then
If lngIndexNew = 1 Then
' Add the new character at the beginning
strNew = Mid$(TESTDATA, lngIndex, 1) & strNew
Else
' Stick it in the middle somewhere
strNew = Left$(strNew, lngIndexNew - 1) & Mid$(TESTDATA, lngIndex, 1) & Mid$(strNew, lngIndexNew)
End If
lngIndex = lngIndex + 1
Exit For
End If
Next
Loop
Thank you for your code. I modify your code to function and test it.
vb Code:
Private Function SortString(ByVal strSource As String) As String Dim strNew As String Dim lngIndex As Long Dim lngIndexNew As Long strNew = Mid$(strSource, 1, 1) lngIndex = 2 Do Until lngIndex = Len(strSource) + 1 For lngIndexNew = 1 To Len(strNew) If Mid$(strSource, lngIndex, 1) < Mid$(strNew, lngIndexNew, 1) Then If lngIndexNew = 1 Then ' Add the new character at the beginning strNew = Mid$(strSource, lngIndex, 1) & strNew Else ' Stick it in the middle somewhere strNew = Left$(strNew, lngIndexNew - 1) & Mid$(strSource, lngIndex, 1) & Mid$(strNew, lngIndexNew) End If lngIndex = lngIndex + 1 Exit For End If Next Loop SortString = strNew End Function Private Sub Command1_Click() MsgBox SortString("9874056213") End Sub
If choose MsgBox SortString("9874056213") it worked.
If choose MsgBox SortString("3152") it is not worked.
Code:'Const TESTDATA = "9874056213"
Const TESTDATA = "3152"
Dim strNew As String
Dim lngIndex As Long
Dim lngIndexNew As Long
Dim bInserted As Boolean
strNew = Mid$(TESTDATA, 1, 1)
lngIndex = 2
Do Until lngIndex = Len(TESTDATA) + 1
bInserted = False
For lngIndexNew = 1 To Len(strNew)
If Mid$(TESTDATA, lngIndex, 1) < Mid$(strNew, lngIndexNew, 1) Then
If lngIndexNew = 1 Then
' Add the new character at the beginning
strNew = Mid$(TESTDATA, lngIndex, 1) & strNew
bInserted = True
Else
' Stick it in the middle somewhere
strNew = Left$(strNew, lngIndexNew - 1) & Mid$(TESTDATA, lngIndex, 1) & Mid$(strNew, lngIndexNew)
bInserted = True
End If
lngIndex = lngIndex + 1
Exit For
End If
Next
If Not bInserted Then
strNew = strNew & Mid$(TESTDATA, lngIndex, 1)
lngIndex = lngIndex + 1
End If
Loop
Thank you very much.