【问题标题】:How to remove a certain substring in C#如何在 C# 中删除某个子字符串
【发布时间】:2013-07-27 04:41:33
【问题描述】:

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

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

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

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

我该怎么做?

【问题讨论】:

  • 如果字符串值为helloworld 并且您想要删除l。这是否意味着它将删除所有匹配的字符串并且输出将是heoword
  • 您应该使用EndsWith(".asm")(或使用Path.GetExtension)来避免像“filename.asmo.doc”这样的极端情况(Contains 将在此处返回误报)

标签: c# string substring


【解决方案1】:

如果您想要结合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】:

你可以使用Path.GetFileNameWithoutExtension(filepath)来做。

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

【讨论】:

  • 如果anotherStringValue 存在于字符串中的任何位置,即使它不是扩展名,也会得到误报。
  • 感谢您的评论。你说的对。我已经编辑了代码
  • 可能还想使用.ToLower()String.Compare 和不敏感标志来避免任何CasE 问题。
【解决方案3】:

不需要 if(),直接使用 :

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

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

【讨论】:

  • 我强烈建议不要这样做;它将删除 所有 次出现,而不仅仅是扩展名。
  • 至少我会检查EndsWith(anotherStringValue)并使用stringValue.SubString(0, stringValue.Length - anotherStringValue.Length)
【解决方案4】:

还有一种单行方法,只删除末尾的“.asm”,而不是字符串中间的任何“asm”:

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

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

要匹配 ".asm" 或 ".ASM" 或任何等效项,您可以进一步指定 Regex.Replace 以忽略大小写:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多