1

From a string, check if it starts with a value 'startsWithCorrectId'...if it does remove the value from the start. Problem being if this value is also found again in the string, it will also remove it. I realise this is what .replace does...but is there something like .startsWith to 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
}

Really what I would like is for '1red-number-1.jpg' to become 'red-number-1.jpg'....NOT 'red-number-.jpg'..replacing all instances of 'startsWithCorrectId' I just want to replace the first instance

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
John
  • 3,965
  • 21
  • 77
  • 163

4 Answers4

0

One solution is to use Regex.Replace():

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

This will remove startsWithCorrectId if it's at the start of the string

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • It's not really what was asked, but it works like a charm in my case (in my context the first occurence is always at first position). – Ishikawa Apr 02 '21 at 10:09
0

if I have undestood your correctly you would need to get a string starting from correctId.Length position

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

if you like extensions:

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);
Artiom
  • 7,694
  • 3
  • 38
  • 45
0
if(file.StartsWith(startsWithCorrectId))
{
    fullImageName = fullImageName.SubString(startsWithCorrectId.Length);    
}
0

You can do so with a regular expression where you can encode the requirement that the string starts at the beginning:

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, "");

Another option is to use a substring, instead of a replace operation. You already know that it's at the start of the string, you can just take the substring starting right after it:

fullImageName = fullImageName.Substring(startsWithCorrectId.Length);
Artiom
  • 7,694
  • 3
  • 38
  • 45
Joey
  • 344,408
  • 85
  • 689
  • 683