How can I extract a substring from this string?

I am trying to extract a string at the end of a url. Example:

C:\this\that\ExtractThisString.exe
             ^^^^^^^^^^^^^^^^^^^^^

      

I am trying to get ExtractThisString.exe

from this line, however it has an unknown quantity \

. I want it to basically grab the url and list everything at the end of it.

+3


source to share


6 answers


To find the last occurrence of a specified character, use

int pos = yourString.LastIndexOf(@"\");

      

then extract the substring



string lastPart = yourString.Substring(pos+1);

      

EDIT I am considering this answer 15 months later because I really missed a key point in the question. The OP is trying to extract the filename, not just find the last occurrence of the given character. Thus, while my answer is technically correct, it is not the best of them all, as the NET has a specialized class for handling filename and paths. This class is called Path and you can find a simple and efficient way to achieve the result using Path.GetFileName as explained in @ Adriano's answer.

I also want to highlight the fact that with the methods from the Path class, you have the advantage of code portability, because the class handles the situation when another operating system uses a different directory separator char.

+3


source


Use the helper methods of the System.IO.Path class. In your case:

string fileName = Path.GetFileName(@"C:\this\that\ExtractThisString.exe");

      



Just for fun, if you need to do it yourself, you should start looking up the index of the last Path.DirectorySeparatorChar . If it is not the last character in the string, you can use String.Substring

to retrieve all text after this index.

+8


source


try it

var str = @"C:\this\that\ExtractThisString.exe";
var filename = str.Substring(str.LastIndexOf("\\")+1);

      

+3


source


Do it once for everything ...

public static string FileAndExtension(this string aFilePath) {
 return aFilePath.Substring(aFilePath.LastIndexOf("\\") + 1);
}

      

"C:\\this\\that\\ExtractThisString.exe".FileAndExtension()

OR

public static string EverythingAfterLast(this string aString, string aSeperator) {
 return aString.Substring(aString.LastIndexOf(aSeperator) + 1);
}

      

"C:\\this\\that\\ExtractThisString.exe".EverythingAfterLast("\\")

+1


source


string path = @"c:\this\that\extractthisstring.exe";
Console.WriteLine(path.Split('\\').Reverse().First());

      

+1


source


I find and use this elegant way using System.IO

string file1 = Path.GetFileName(@"C:\this\that\ExtractThisString.exe");

or if you want no extension

string file2 = Path.GetFileNameWithoutExtension(@"C:\this\that\ExtractThisString.exe");

or just an extension

string ext = Path.GetExtension(@"C:\this\that\ExtractThisString.exe");

0


source







All Articles