使用下划线作为标记分割字符串

Arg*_*gon 5 vb.net string filenames split

自从我分割字符串以来已经有一段时间了,但是我需要使用“_”下划线作为分割字符串的标记来分割和重新排列文本。

例如:

TOM_here_was
Run Code Online (Sandbox Code Playgroud)

那么就会变成

here_was_TOM
Run Code Online (Sandbox Code Playgroud)

我如何在 VB.net 中做到这一点?

Tim*_*ter 1

订购的规则是什么?

根据split,使用Split("_"c)得到一个数组:

Dim tokens = "TOM_here_was".Split("_"c)
Run Code Online (Sandbox Code Playgroud)

现在您已经拥有了所有部件,例如,如果您想要随机顺序(因为不清楚):

tokens = tokens.OrderBy(Function(s) Guid.NewGuid()).ToArray()
Run Code Online (Sandbox Code Playgroud)

更新按照。你的评论:

我有一个带有客户编号的文件名,后面的数字是开始日期,最后一个数字是结束日期。例如1111_20140201_20140228。汤姆在这里可能不是一个好例子

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
Run Code Online (Sandbox Code Playgroud)

如果你想对目录中的文件进行排序,你可以使用 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
Run Code Online (Sandbox Code Playgroud)