Link to home
Start Free TrialLog in
Avatar of Richard Kreidl
Richard KreidlFlag for United States of America

asked on

Split and swap string

If I have the following string:

Saturday 12:23am  

I want to change it to:

12:23am Saturday

Swapping the two fields.

If just the time is present:

12:23am    

don't do anything.

thanks
ASKER CERTIFIED SOLUTION
Avatar of Jens Fiederer
Jens Fiederer
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The preceding will work for arbitrary space delimited strings - since reversing a singleton array does nothing, an absence of a space will produce nothing.

Obviously, if you want error checking (require only two words, make sure of legitimate days of week, etc.), you can do that before you call Array.Reverse.
Avatar of doobdave
doobdave

Hi rkckjk,

You can try the following:

Private Function ParseDate(pDateToParse as String) as String

Dim strSplitString() as String
strSplitString = Split(pDateToParse, " ") ' This function splits the string into an array of strings, splitting them on the specified character (" ", one space, in this case)

If strSplitString.Length = 2 Then
  Return strSplitString(1) & " " & strSplitString(0)
ElseIf strSplitString.Length =1 Then
  Return strSplitString(0)
End If

End Function

However, if you are working solely with dates, there are several useful functions for doing such things.
Have a look at the MSDN for "DateTime Structure"

HTH,
David
oops, sorry jens,
I was writing that while you must've posted!

rkckjk, Jensfiederer's solution is more elegant (using the array.reverse() & string.join() functions - which I had forgotten about!) so I would go with that.

Regards,
David
Avatar of Richard Kreidl

ASKER

It swaps the string, but maybe I didn't pose my question well.

I only want the string swapped if the data is entered incorrectly:

Incorrectly entered:
Saturday 12:23am

Correctly enetered:
12:23am Saturday

Then instead of a simple
     Array.Reverse(sX)
you can do
        If sX.Length > 1 Then
            If sX(1).Length > 0 Then
                If Char.IsDigit(sX(1).Chars(0)) Then
                    Array.Reverse(sX)
                End If
            End If
        End If