Question

Its been a while since Ive split strings however i need to split and rearange text ussing "_" underscores as markers where to split the string.

eg:

TOM_here_was

would then become

here_was_TOM

how do I do that in VB.net?

Was it helpful?

Solution

What is the rule for the ordering?

According to the split, use Split("_"c) to get an array:

Dim tokens = "TOM_here_was".Split("_"c)

Now you have all parts, if you want a random order for example (since it's not clear):

tokens = tokens.OrderBy(Function(s) Guid.NewGuid()).ToArray()

Update acc. your comment:

I have a file name with a client number then the number that follows is a starting date and the last number is an end date. eg 1111_20140201_20140228. tom was here probably not a good example

Dim path = "C:\Temp\1111_20140201_20140228.txt"
Dim fileName = System.IO.Path.GetFileNameWithoutExtension(path)
Dim tokens = fileName.Split("_"c)
If tokens.Length = 3 Then
    Dim client = tokens(0)
    Dim startDate, endDate As Date
    Dim parsableStart = Date.TryParseExact(tokens(1),
                                      "yyyyMMdd",
                                      Globalization.CultureInfo.InvariantCulture,
                                      Globalization.DateTimeStyles.None,
                                      startDate)
    Dim parsableEnd = Date.TryParseExact(tokens(2),
                                      "yyyyMMdd",
                                      Globalization.CultureInfo.InvariantCulture,
                                      Globalization.DateTimeStyles.None,
                                      endDate)
    If parsableStart AndAlso parsableEnd Then
        Console.WriteLine("Client: {0} Start: {1} End: {2}", client, startDate, endDate)
    End If
End If

If you want to order the files in a directory you could use LINQ:

Dim startDate, endDate As Date
Dim fileNames = System.IO.Directory.EnumerateFiles("C:\Temp\", "*.*", SearchOption.TopDirectoryOnly)
Dim orderedFilenames =
    From path In fileNames
    Let fileName = System.IO.Path.GetFileNameWithoutExtension(path)
    Let tokens = fileName.Split("_"c)
    Where tokens.Length = 3
    Let client = tokens(0)
    Let startDateParsable = Date.TryParseExact(tokens(1), "yyyyMMdd", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, startDate)
    Let endDateparsable = Date.TryParseExact(tokens(2), "yyyyMMdd", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, endDate)
    Where startDateParsable AndAlso endDateparsable
    Order By startDate, endDate
    Select New With { fileName, client, startDate, endDate }

For Each fn In orderedFilenames
    Console.WriteLine("File: {0} Client: {1} Start: {2} End: {3}", fn.fileName, fn.client, fn.startDate, fn.endDate)
Next

OTHER TIPS

Dim myString = "TOM_here_was"
Dim splitArray() As String

splitArray = Split(myString, "_", -1) 

In this example, splitArray() would have the following values:

  • splitArray[0] = TOM
  • splitArray[1] = here
  • splitArray[2] = was

After that, you can use the splitArray to create a new string however you want.

Since you haven't specified how you're re-organizing the new string, I can't really help other than to do something like:

Dim newString = splitArray[0] & "_" & splitArray[2] & "_" & splitArray[1]

to get: TOM_was_here

I've made a generic usage function for your problem:

''' <summary>
''' Splits an String and rotates an amount of splitted tokens.
''' </summary>
''' <param name="String">Indicates the string to split and rotate.</param>
''' <param name="Delimiter">Indicates the delimiter to split.</param>
''' <param name="Rotation">Indicates the rotation count.</param>
''' <returns>System.String.</returns>
''' <exception cref="Exception">Rotation index out of range.</exception>
Private Function SplitAndRotate(ByVal [String] As String,
                                ByVal Delimiter As Char,
                                ByVal Rotation As Integer) As String

    Dim Parts As String() = [String].Split(Delimiter)

    If Rotation >= Parts.Length Then
        Throw New Exception("Rotation index out of range.")
    End If

    Return String.Format("{0}{1}",
                         String.Join(Delimiter,
                                     From s As String In Parts Skip Rotation) & CStr(Delimiter),
                         String.Join(Delimiter,
                                     From s As String In Parts Take Rotation))

End Function

Usage:

    Dim str As String = SplitAndRotate("TOM_here_was", "_"c, 1)
    ' Result: here_was_TOM

Explanation

I will tell you the most easiest way. Here is how I would do it. First we will take it as a string test and we will use test.Split() and specify splitting from underscore. And then store the split parts in the variable parts.

We will join them together in Label1 (You can do it in variable or whatever you want).

Code And Example

Public Class Form1
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
             Dim test As String = "TOM_Here_was"
             Dim parts As String() = test.Split("_"c)
             If parts.Length >= 3 Then
                  Label1.Text = parts(1) & "_" & parts(2) & "_" & parts(0)
             End If

        End Sub
End Class

I hope it would work perfectly!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top