仅删除字符串中的第一个匹配项

时间:2016-10-07 09:55:29

标签: c#

从一个字符串中,检查它是否以值'startsWithCorrectId'开头...如果确实从开头删除了值。问题是如果在字符串中再次找到此值,它也将删除它。我意识到这就是.replace所做的......但是有什么像.startsWith到RemoveAtStart吗?

string startsWithCorrectId = largeIconID.ToString();
//startsWithCorrectId will be '1'

string fullImageName = file.Replace("_thumb", "");
//fullImageName will be "1red-number-1.jpg"

//file will be '1red-number-1_thumb.jpg'
if(file.StartsWith(startsWithCorrectId))
{
    fullImageName = fullImageName.Replace(startsWithCorrectId, "");
    //so yes this is true but instead of replacing the first instance of '1'..it removes them both
}

我真想要的是'1red-number-1.jpg'成为'red-number-1.jpg'....不是'red-number-.jpg'..替换所有'' startsWithCorrectId'我只想替换第一个实例

4 个答案:

答案 0 :(得分:0)

一种解决方案是使用Regex.Replace()

fullImageName = Regex.Replace(fullImageName, "^" + startsWithCorrectId, "");

如果它位于字符串

的开头,则会删除startsWithCorrectId

答案 1 :(得分:0)

如果我正确地取消你的正确,你需要从correctId.Length位置开始获取一个字符串

 if(fullImageName .StartsWith(startsWithCorrectId))
     fullImageName = fullImageName .Substring(startsWithCorrectId.Length);

如果你喜欢扩展名:

public static class StringExtensions{

   public static string RemoveFirstOccuranceIfMatches(this string content, string firstOccuranceValue){
        if(content.StartsWith(firstOccuranceValue))
            return content.Substring(firstOccuranceValue.Length);
        return content;
   }
}


//...
fullImageName = fullImageName.RemoveFirstOccuranceIfMatches(startsWithCorrectId);

答案 2 :(得分:0)

if(file.StartsWith(startsWithCorrectId))
{
    fullImageName = fullImageName.SubString(startsWithCorrectId.Length);    
}

答案 3 :(得分:0)

您可以使用正则表达式来执行此操作,您可以在其中编码字符串从头开始的要求:

var regex = "^" + Regex.Escape(startsWithCorrectId);
// Replace the ID at the start. If it doesn't exist, nothing will change in the string.
fullImageName = Regex.Replace(fullImageName, regex, "");

另一种选择是使用子字符串,而不是替换操作。你已经知道它在字符串的开头,你可以从它后面的子字符串开始:

fullImageName = fullImageName.Substring(startsWithCorrectId.Length);