Get part of string

obrien.james

Member
Joined
Sep 11, 2009
Messages
15
Programming Experience
Beginner
Hi,

I want to make a function that takes a string and then returns only a specific part of that string.

The string the function will take is a path to a file such as

D:\Folder\Folder2\Untitled Document_1_2.tif

What i want the function to do is return the

Untitled Document_1

Portion of the supplied string.

I'm not sure how to do this and wondered if anyone on here could help me.

Thanks

James
 
You may need to do this in two stages. First extract the filename root using this:
VB.NET:
Path.GetFileNameWithoutExtension(fileName)
You need to provide more information on criteria for selecting the string you want from the result. For example if the filename is
myfile.txt
- what do you want? You may be able to use RegEx or write a little function. Let us know and we'll try to help.
 
If that's the pattern, then try this:

VB.NET:
        Dim fpath As String = "D:\Folder\Folder2\Untitled Document_1_2.tif"
        Dim fname As String = Path.GetFileNameWithoutExtension(fpath)
        Dim partofthestring As String = fname.Substring(0, fname.Length - (fname.Length - fname.LastIndexOf("_"c)))
        Console.WriteLine("Result: " & partofthestring & New FileInfo(fpath).Extension)
 
Last edited:
Use the LastIndexOf method to locate the last slash. Then use the IndexOf method to locate the first underscore. Finally, use the Substring method to extract the part of the string between the two locations.

The following shows two ways to get the same result:

VB.NET:
		Dim mystr As String = "D:\Folder\Folder2\Untitled Document_1_2.tif"
		Dim loc1, loc2 As Integer, substr As String
		loc1 = mystr.LastIndexOf("\")
		loc2 = mystr.IndexOf("_")
		substr = mystr.Substring(loc1 + 1, loc2 - loc1 + 1)
		MessageBox.Show(substr)

		'or

		Dim loc As Integer, substr1, substr2 As String
		loc = mystr.LastIndexOf("\")
		substr1 = mystr.Substring(loc + 1)
		loc = substr1.IndexOf("_")
		substr2 = substr1.Substring(0, loc + 2)
		MessageBox.Show(substr2)
 
Last edited:
Back
Top