如何删除C#中的某个子字符串

时间:2013-07-26 19:22:33

标签: c# string substring

所以我在C#项目中有一些文件扩展名,如果它们在那里我需要从文件名中删除它们。

到目前为止,我知道我可以检查子字符串是否在文件名中。

if (stringValue.Contains(anotherStringValue))
{  
    // Do Something // 
}

因此,如果说stringValuetest.asm,然后它包含.asm,我想以某种方式从.asm中移除stringValue

我该怎么做?

4 个答案:

答案 0 :(得分:7)

您可以使用Path.GetFileNameWithoutExtension(filepath)来执行此操作。

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

答案 1 :(得分:7)

如果你想要一个与Path库结合的“黑名单”方法:

// 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);
}

处理的例子:

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

答案 2 :(得分:6)

不需要if(),只需使用:

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

如果在anotherStringValue中找不到stringValue,则不会发生任何更改。

答案 3 :(得分:3)

另外还有一种单行方法可以在最后删除“.asm”,而不是在字符串中间删除任何“asm”:

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

“$”匹配字符串的结尾。

要匹配“.asm”或“.ASM”或任何equivlanet,您可以进一步指定Regex.Replace以忽略大小写:

using System.Text.RegularExpresions;
...
stringValue = Regex.Replace(stringValue,".asm$","",RegexOptions.IgnoreCase);
相关问题