How to get a snippet of a string?

10

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

    
asked by anonymous 09.10.2014 / 15:56

2 answers

14

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

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

The second parameter gives the position from where the search should begin.

Then you need to find the third bar to know where to get it:

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

Have another way with Split which seems simpler and more flexible and may be more useful in some cases (but can also be a waste on 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.

See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .

    
09.10.2014 / 16:06
8

(Although Maniero's response is quite good, it's always nice to add other possibilities.)

One workaround 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 . Using the + character ensures that there is at least one character between these two slashes.

(Brief introduction about regular expressions).

    
09.10.2014 / 16:38