【问题标题】:Split string using underscore as marker使用下划线作为标记分割字符串
【发布时间】:2014-04-04 15:42:29
【问题描述】:

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

例如:

TOM_here_was

会变成

here_was_TOM

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

【问题讨论】:

  • 我会先使用 '=' 作为分隔符拆分字符串,然后以不同的顺序创建一个新字符串。
  • 排序规则是什么?
  • @ Tim qua 排序规则,我有一个带有客户编号的文件名,然后后面的数字是开始日期,最后一个数字是结束日期。例如 1111_20140201_20140228。汤姆在这里可能不是一个很好的例子

标签: vb.net string split filenames


【解决方案1】:

排序规则是什么?

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

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

现在你有了所有的零件,如果你想要一个随机的顺序(因为不清楚):

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

更新 acc。你的评论:

我有一个带有客户编号的文件名,然后是后面的编号 是开始日期,最后一个数字是结束日期。例如 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

如果要对目录中的文件进行排序,可以使用 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

【讨论】:

    【解决方案2】:
    Dim myString = "TOM_here_was"
    Dim splitArray() As String
    
    splitArray = Split(myString, "_", -1) 
    

    在本例中,splitArray() 将具有以下值:

    • splitArray[0] = 汤姆
    • splitArray[1] = 此处
    • splitArray[2] = 是

    之后,您可以根据需要使用 splitArray 创建一个新字符串。

    由于您尚未指定如何重新组织新字符串,因此除了执行以下操作之外我无能为力:

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

    获取:TOM_was_here

    【讨论】:

      【解决方案3】:

      我为你的问题做了一个通用的使用函数:

      ''' <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
      

      用法:

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

      【讨论】:

        【解决方案4】:

        说明

        我会告诉你最简单的方法。这是我将如何做到的。首先,我们将其作为字符串test,我们将使用test.Split() 并指定从下划线拆分。然后将拆分的部分存储在变量parts中。

        我们将在Label1 中将它们联合起来(您可以使用变量或任何您想要的方式进行操作)。

        代码与示例

        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
        

        我希望它能完美运行!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-30
          • 2013-05-12
          相关资源
          最近更新 更多