gundog48
gundog48

Reputation: 3

Selectively manipulate a string in VB

I'm trying to create a program to automate a certain conversion process which is required to add new playermodels to game servers which currently involves lots of repetitive manual work.

However, I'm struggling to get over this one seemingly simple bit! The user selects a file at the start of the process using the file dialog which throws out a string of the directory like this:

"M:\User\Documents\Playermodel Program\Raw Addon\Stalker Playermodel\models\player\zelpa\model.mdl"

I want to shorten this string down to:

"models\player\zelpa\model.mdl"

The issue being, that anything before there could change. So can the file name, and any directory between 'models' and the folder the actual model is in! So the only sure bit to go from is /models/ which will always be there.

What I'd like to do is take the string and delete everything up to a part of the string that equals "\models\" and delete everything up to it, as well as the first "\". It needs to be a search for "\models\" and not "models\" as somebody may have a folder named "playermodels" which would throw it off!

How can I achieve this? For a seemingly simple problem, I fear it may have a very complex solution!

Upvotes: 0

Views: 43

Answers (2)

Derek
Derek

Reputation: 8763

Because LINQ is so much fun...

Dim s As String = "M:\User\Documents\Playermodel Program\Raw Addon\Stalker Playermodel\models\player\zelpa\model.mdl"
Dim returnValue As String = String.Join("\", s.Split("\".ToCharArray()).Reverse().Take(4).Reverse())

This splits by "\" and takes the last four parts. It does this by reversing the list, taking the first four parts, and then reversing it again. Then it joins them back together using "\".

Upvotes: 0

Mark
Mark

Reputation: 8150

If I am following along correctly, you can just use String.IndexOf to find the \models\ part, and String.Substring to extract the part of the path you are interested in:

Dim fileName = "M:\User\Documents\Playermodel Program\Raw Addon\Stalker Playermodel\models\player\zelpa\model.mdl"
Dim partPath = fileName.Substring(fileName.IndexOf("\models\") + 1)

Upvotes: 1

Related Questions