Trim characters from a string

I need to trim a substring from a string if that substring exists.

In particular, if the line is "MainGUI.exe", then I need it to become "MainGUI", by trimming ".exe" from the line.

I tried this:

     String line = "MainGUI.exe";
     char[] exe = {'e', 'x', 'e', '.'};
     line.TrimEnd(exe);

This gives me the correct answer for "MainGui.exe", but for something like "MainGUIe.exe" it does not work, giving me "MainGUI" instead of "MainGUIe".

I am using C #. Thanks for the help!

+5
source share
6 answers

Path System.IO, . , , .. .

var filename = Path.GetFileNameWithoutExtension(line);

"MainGui", , , , , .exe, .exe, , . , String.EndsWith(), Path.GetExtension().

+15

Path.GetFileNameWithoutExtension , .

string line = "MainGUI.exe";
string fileWithoutExtension = Path.GetFileNameWithoutExtension(line);

, .exe, . .exe, :

string ext = Path.GetExtension(line).ToLower();
string fileWithoutExtension = ext == ".exe" 
                               ? Path.GetFileNameWithoutExtension(line) 
                               : line;
+13

If you always trim the ".exe", you can trim the last 4 characters regardless of the rest of the line.

line.Substring(0, line.Length - ".exe".Length);
+3
source
string line = "MainGUI.exe";
if (line.EndsWith(".exe"))
    line = line.Substring(0, line.Length - 4);
+3
source

Since no file extension has a period (.) Inside it, you can use this:

String line = "MainGUI.exe";
line = line.Substring(0, line.LastIndexOf('.'));
0
source

All Articles