Split String with . Split - C#

Asked

Viewed 2,020 times

2

Good morning, everyone,

I am trying to pick up a specific part of a string in Visual Studio, in which case the string in question is a directory path: "C: Users User File-2018.txt" I would like to try to pick up only what comes after the last " ", I tried to do

string[] texto = caminho.Split("\");
string resultado = texto[3];

But the error code, saying that it cannot convert character to string, could anyone help me in this situation by honeycomb? I thank you in advance. Obs: "path" variable is string type

  • Wesley, your logic is right, but change Split("\"); for Split('\');. In other words, change double quotes to single quotes.

  • Hello Matheus, thank you for the reply, as it turned out I managed to settle with a solution down there. I thank you again for your reply.

  • You need to understand why your code doesn’t work.

2 answers

3

.Split() does not accept double quotes, single quotes only, ex:

string caminho = @"C:\Users\Usuario\Arquivo-2018.txt";
string[] texto = caminho.Split('\\');
string resultado = texto[3]; //Arquivo-2018.txt

Source: .Split()

  • 1

    In simple things like this, it is likely that already have several duplicates that shows how to make the question. It is better to close them.

  • @Maniero yes it is better to close.

2


Try to use the method Substring, would look like this:

string resultado = caminho.Substring(caminho.LastIndexOf(@"\") + 1);

Explanation: the method Substring has the function of returning us some "piece" of our original string. The way we are using requires us the start index of our new string, for this we use the method LastIndexOf to say that we want the index of the last \ in its string + 1 to pick from the next character after the last \.

  • Hello Peter, thank you so much, it worked out here. I’ll just wait to spend the time to mark your reply as solution. Thank you again.

  • For nothing, I thank you!

  • You who have started now and are answering a lot of things, in simple things like that, you probably already have several duplicates that show you how to do the question. Better close them up.

Browser other questions tagged

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