Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a particular part of a String

Tags:

excel

vba

I am writing a macro in Excel where I need to get a substring from a String. It's like this.

~/tester/test/hai/bye
~/stack/overflow/hai/bye

In the above cases I need to take the String tester from the first one and stack from the second one. I tried using InStr but it's not useful. Can anyone help?

like image 671
Harish Avatar asked Mar 30 '10 06:03

Harish


People also ask

How do you get a specific part of a string in python?

Python provides different ways and methods to generate a substring, to check if a substring is present, to get the index of a substring, and more. start - The starting index of the substring. stop - The final index of a substring. step - A number specifying the step of the slicing.

How do you get a substring from a string?

To extract a substring that begins at a specified character position and ends before the end of the string, call the Substring(Int32, Int32) method. This method does not modify the value of the current instance. Instead, it returns a new string that begins at the startIndex position in the current string.

Is substr () and substring () are same?

The difference between substring() and substr()The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .

How can I take part of a string in C#?

We can use the Substring method and pass it starting index 0 and length of the substring 12 to get the first 12 char substring from a string. The following code snippet is an example of retrieving a 12 chars substring from a string. string authorName = bio. Substring(0, 12);


1 Answers

You can do this using the InStr and Mid functions. Use the InStr function to find the occurrences of the / and then use Mid to get the part of the string that you are interested in.

Try this:

Function ExtractFirstPartOfPath(path as String) as String

  Dim first, second as Integer

  first = InStr(path, "/")
  second = InStr(first + 1, path, "/")

  ExtractFirstPartOfPath = Mid(path, first + 1, second - first - 1)

End Function

This function will produce the desired results.

like image 72
Rune Grimstad Avatar answered Oct 02 '22 07:10

Rune Grimstad