How to get a snippet of a string?

Asked

Viewed 19,497 times

10

I have a string like this: ~/Areas/Teste/Views/home/index.cshtml I just need the word that comes right after ~/Areas/, in the case Teste (remembering that this word may vary in size). How do?

2 answers

15


You need to find where the first bar is and have the search done by the second starting from where the first one is. The . NET has the method Indexof() to locate a specific text in another. It would look like this:

var inicioPalavra = texto.IndexOf('/', texto.IndexOf('/') + 1);

The second parameter provides the position from where to start the search.

Then you need to figure out the third bar to know where to pick up:

var palavra = texto.Substring(inicioPalavra + 1, texto.IndexOf('/', inicioPalavra + 1) - inicioPalavra - 1);

There’s another way with Split() which seems simpler and more flexible and may be more useful in some cases (but can also be a waste in others):

var palavras = texto.Split('/');
var palavra = palavras[2]; //está pegando a terceira palavra do texto separado por barras

Now it’s easy to adapt to other similar cases.

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • Thank you so much for the help, the two ways worked very well :D

8

(Despite the reply of the Maniero being quite good, and always interesting to add other possibilities.)

An alternative solution would be to use regular expressions to capture the text you need:

const string source = "~/Areas/Teste/Views/home/index.cshtml";
Regex regex = new Regex("^~/Areas/(?<output>[a-zA-Z0-9]+)/*/.*$");
GroupCollection capturas = regex.Match(source).Groups;
Console.WriteLine(capturas["output"]);

(Result in .Netfiddle)

In this case the regular expression "^~/Areas/(?<output>[a-zA-Z0-9]+)/*/.*" will capture all letters and numbers between the second and third parentheses and place them in a group called output. The use of character + ensures that there is at least one character between these two bars.

(Brief introducing on regular expressions).

  • 2

    It’s because I hate Regex :P

  • 4

    And normal :P when you use regex to solve a problem, you get two. But I still think a light introduction to regex is good.

  • 2

    Thank you, it is always important to know other ways to resolve :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.