So I have a few file extensions in my C# projects and I need to remove them from the file name if they are there.
So far I know I can check if a Sub-string is in a File Name.
if (stringValue.Contains(anotherStringValue))
{
// Do Something //
}
So if say stringValue
is test.asm
, and then it contains .asm
, I want to somehow remove the .asm
from stringValue
.
How can I do this?
The first and most commonly used method to remove/replace any substring is the replace() method of Java String class. The first parameter is the substring to be replaced, and the second parameter is the new substring to replace the first parameter.
Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
We have removeChar() method that will take a address of string array as an input and a character which you want to remove from a given string. Now in removeChar(char *str, char charToRemove) method our logic is written.
if you want a "blacklist" approach coupled with the Path
library:
// list of extensions you want removed
String[] badExtensions = new[]{ ".asm" };
// original filename
String filename = "test.asm";
// test if the filename has a bad extension
if (badExtensions.Contains(Path.GetExtension(filename).ToLower())){
// it does, so remove it
filename = Path.GetFileNameWithoutExtension(filename);
}
examples processed:
test.asm = test
image.jpg = image.jpg
foo.asm.cs = foo.asm.cs <-- Note: .Contains() & .Replace() would fail
You can use Path.GetFileNameWithoutExtension(filepath) to do it.
if (Path.GetExtension(stringValue) == anotherStringValue)
{
stringValue = Path.GetFileNameWithoutExtension(stringValue);
}
No need for the if(), just use :
stringValue = stringValue.Replace(anotherStringValue,"");
if anotherStringValue
is not found within stringValue
, then no changes will occur.
One more one-liner approach to getting rid of only the ".asm" at the end and not any "asm" in the middle of the string:
stringValue = System.Text.RegularExpressions.Regex.Replace(stringValue,".asm$","");
The "$" matches the end of the string.
To match ".asm" or ".ASM" or any equivlanet, you can further specify Regex.Replace to ignore case:
using System.Text.RegularExpresions;
...
stringValue = Regex.Replace(stringValue,".asm$","",RegexOptions.IgnoreCase);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With