user1447679
user1447679

Reputation: 3240

With vb.net, how can I split this filename/string?

Dim suffix As String = "_version"

I have a file called "Something_version1.jpg"

I need to split this so that I get "Something_version"

The following gets me "1.jpg"

filename = filename.Split(New String() {suffix}, StringSplitOptions.None)(1)

And the following gets me "Something"

filename = filename.Split(New String() {suffix}, StringSplitOptions.None)(0)

But what I need is "Something_version"

The suffix is dynamic, and can change.

Hope this is easier than I'm making it.

Thank you.

Upvotes: 0

Views: 563

Answers (2)

Geoffrey Wiseman
Geoffrey Wiseman

Reputation: 5637

If you don't care about the "1.jpg" part at all, and all you want is the suffix and the part before the suffix, you can do what you have above (the second one) to get the prefix, and simply concatenate the prefix and suffix to get the answer you're looking for.

The split call might be overkill but it will do the job.

Upvotes: 1

Paul Ishak
Paul Ishak

Reputation: 1093

Try this!

Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim suffix As String = "_version"
        Dim searchThis As String = "something_version1.png"
        MsgBox(GetPrefix(suffix, searchThis))
    End Sub
    Function GetPrefix(suffix As String, searchThis As String) As String
        Dim suffixLocation As Integer = searchThis.IndexOf(suffix) + suffix.Count
        Return searchThis.Substring(0, suffixLocation)
    End Function
End Class

Upvotes: 0

Related Questions