How to remove a specific substring in C #

So, I have several file extensions in my C # projects, and I need to remove them from the file name, if any.

So far I know that I can check if the substring is in the 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 .asm from stringValue .

How can i do this?

+6
source share
4 answers

if you want to use the blacklist in conjunction 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); } 

processed examples:

 test.asm = test image.jpg = image.jpg foo.asm.cs = foo.asm.cs <-- Note: .Contains() & .Replace() would fail 
+7
source

You can use Path.GetFileNameWithoutExtension (file path) to do this.

 if (Path.GetExtension(stringValue) == anotherStringValue) { stringValue = Path.GetFileNameWithoutExtension(stringValue); } 
+7
source

No need for if (), just use:

 stringValue = stringValue.Replace(anotherStringValue,""); 

if anotherStringValue not found inside stringValue , then no changes will occur.

+6
source

Another one-line approach to getting rid of ".asm" at the end, and not to "asm" in the middle of the line:

 stringValue = System.Text.RegularExpressions.Regex.Replace(stringValue,".asm$",""); 

"$" matches the end of the line.

To match ".asm" or ".ASM" or any equivalent, you can optionally specify Regex.Replace to ignore case:

 using System.Text.RegularExpresions; ... stringValue = Regex.Replace(stringValue,".asm$","",RegexOptions.IgnoreCase); 
+3
source

Source: https://habr.com/ru/post/950389/


All Articles