Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim characters from a string

Tags:

string

c#

trim

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!

like image 378
nat Avatar asked Jun 27 '12 16:06

nat


1 Answers

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.

like image 65
James Michael Hare Avatar answered Nov 06 '22 07:11

James Michael Hare