【问题标题】:Determine if a string contains a substring at a specific position确定字符串是否在特定位置包含子字符串
【发布时间】:2014-01-29 19:43:35
【问题描述】:

我需要检查某个文件名是否包含用户指定的子字符串,但我似乎无法正确获取语法(我是 C# 新手)。我应该使用星号,但我不确定应该如何格式化(请参阅下面的代码)。

if (fileInfo[i].Name == ("{0} * . * ", partialName) || fileInfo[i].Name == (" * {0}. * ", partialName))

【问题讨论】:

    标签: c# string file substring


    【解决方案1】:

    尝试使用string 中的Contains 方法,作为示例:

    if (fileInfo[i].Name.Contains(partialName)) 
    {
       // your code
    }
    

    如果您想从名称中删除扩展名,请尝试使用Path 静态类和GetFileNameWithoutExtension 方法,例如:

    string fileName = System.IO.Path.GetFileNameWithoutExtension(fileInfo[i].Name);
    
    if (fileName.Contains(partialName)) 
    {
       // your code
    }
    

    现在,如果您想忽略区分大小写的字符串,请尝试使用IndexOf 方法,例如:

    if (fileInfo[i].Name.IndexOf(partialName, StringComparison.OrdinalIgnoreCase) >= 0)
    {
       // your code
    }
    

    或应用 Path.GetFileNameWithoutExtension 以在 IndexOf 上使用。

    【讨论】:

    • 我必须使用 * ,另外,使用 .Contains 还会检查文件扩展名,因为它包含在字符串中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多