nat
nat

Reputation: 145

Trim characters from a string

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

Specifically, if the string is "MainGUI.exe", then I need it to become "MainGUI", by trimming ".exe" from the string.

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 doesn’t work, giving me "MainGUI" instead of "MainGUIe".

I am using C#. Thanks for the help!

Upvotes: 5

Views: 1404

Answers (6)

Sandeep Shankar
Sandeep Shankar

Reputation: 81

As no file extension has a dot (.) within it, you are safe to use this:

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

Upvotes: 0

Kevin Anderson
Kevin Anderson

Reputation: 589

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

Upvotes: 3

James Michael Hare
James Michael Hare

Reputation: 38397

Use the Path static class in System.IO namespace, it lets you strip extensions and directories from file names easily. You can also use it to get the extension, full path, etc. It's a very handy class and well worth looking into.

var filename = Path.GetFileNameWithoutExtension(line);

Gives you "MainGui", this is, of course, assuming you want to trim any file extension or you know your file is always going to be a .exe file, if you want to only trim extensions off of .exe files, however, and leave it on others. You can test first, either by using String.EndsWith() or by using the Path.GetExtension() method.

Upvotes: 15

Brad
Brad

Reputation: 12245

If you are always trimming ".exe" you can trim the last 4 characters off regardless of the rest of the string.

line.Substring(0, line.Length - ".exe".Length);

Upvotes: 3

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

The Path class has a GetFileNameWithoutExtension.

Upvotes: 7

Reed Copsey
Reed Copsey

Reputation: 564333

I would use Path.GetFileNameWithoutExtension instead of string manipulation to handle this.

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

If you only want to strip off the extension if it's .exe, you can check for that as well. The following will only strip off extensions of .exe, but leave all other extensions intact:

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

Upvotes: 13

Related Questions