如何在vb.net中拆分字符串名称

时间:2015-01-24 17:08:19

标签: vb.net

编辑:(对不起我写的不明确的困境)

我已将名称更改为" 2015-02-12a00.12.20a67"请取悦"名称"我这里只是一个图像文件名的示例,我将从文件夹中读取。我唯一的要求是输出。我希望文件名分为三个(日期,时间和速度),以便我可以将它们存储到数据库中。

str1 = 2015-02-12
str2 = 00:12:20
str3 = 67

我怎么能在vb.net中这样做?我找到了这段代码

Dim TestString As String = "apple pear banana  " 
Dim TestArray() As String = Split(TestString)
Dim LastNonEmpty As Integer = -1

For i As Integer = 0 To TestArray.Length - 1
    If TestArray(i) <> "" Then
        LastNonEmpty += 1
        TestArray(LastNonEmpty) = TestArray(i)
    End If 
Next 

但它并不符合我的需要。 有人请帮帮我..

3 个答案:

答案 0 :(得分:1)

我认为这是你正在寻找的东西:

Dim input = "image2015021400122067"
Const Prefix = "image"
Const YearLength = 4
Const NonYearDateTimeFieldLengths = 2
Dim year = input.Substring(Prefix.Length, YearLength)
Dim month = input.Substring(Prefix.Length + YearLength, NonYearDateTimeFieldLengths)
Dim day = input.Substring(Prefix.Length + YearLength + NonYearDateTimeFieldLengths, NonYearDateTimeFieldLengths)
Const DateSeparator = "-"c
Dim str1 = String.Join(DateSeparator, {year, month, day})
Dim hours = input.Substring(CInt(Prefix.Length + YearLength + NonYearDateTimeFieldLengths * 2), NonYearDateTimeFieldLengths)
Dim minutes = input.Substring(CInt(Prefix.Length + YearLength + NonYearDateTimeFieldLengths * 3), NonYearDateTimeFieldLengths)
Dim seconds = input.Substring(CInt(Prefix.Length + YearLength + NonYearDateTimeFieldLengths * 4), NonYearDateTimeFieldLengths)
Const TimeSeparator = ":"c
Dim str2 = String.Join(TimeSeparator, {hours, minutes, seconds})
Dim str3 = input.Substring(CInt(Prefix.Length + YearLength + NonYearDateTimeFieldLengths * 5), NonYearDateTimeFieldLengths)

请注意,此代码做了一些假设:

  1. 您的字符串始终以image
  2. 开头
  3. 字段将始终相同&#34; width&#34;,即年份将始终为4个字符(duh!),其他日期/时间字段将为2个字符,必要时填充为零,就像你提供的输入字符串。

答案 1 :(得分:1)

您可以使用DateTime.ParseExact和字符串格式

    Dim datex = "Image2015021400122067"

    Dim dt = DateTime.ParseExact(datex, "'Image'yyyyMMddhhmmssff", Nothing)

    Dim s1 = dt.ToString("yyyy-MM-dd")

    Dim s2 = dt.ToString("HH:mm:ss")

    Dim s3 = dt.ToString("ff")

无需使用子字符串,格式模式中会忽略“Image”  您可以在此处https://dotnetfiddle.net/BAwrUv

进行测试

答案 2 :(得分:-2)

基于:

.NET 4.5

使用Split

的VB.NET程序
Module Module1

Sub Main()
' We want to split this input string
Dim s As String = "2015-02-12a00.12.20a67"

' Split string based on spaces
Dim words As String() = s.Split(New Char() {"a"c})

' Use For Each loop over words and display them
Dim word As String
For Each word In words
    Console.WriteLine(word)
Next
End Sub

End Module

输出

2015-02-12
00.12.20
67

我认为这可以帮到你很多。 这是链接http://www.dotnetperls.com/split-vbnet