Home > Mobile >  remove specific text from middle of string (only first occurrence from end of a string)
remove specific text from middle of string (only first occurrence from end of a string)

Time:11-19

I need to remove a specific value from middle of a string and only its first occurrence from end of the string e.g.

I'm having a URL as url : https://something/ABCD/EFGH/IJKL/ABCD?id=1234567910

In above url string I need to replace last "ABCD" with "NEW" as below:

url : https://something/ABCD/EFGH/IJKL/NEW?id=1234567910

currently how I'm doing this is

using System;  
  
namespace StringReplaceSample  
{  
   public class Program  
    {  
        public static void Main(string[] args)  
        {  
        string pageid = "?id=1234567910";//its something i can retrive or get
        
        string example = "https://something/ABCD/EFGH/IJKL/ABCD?id=1234567910";
        String[] breakApart = example.Split('/');
        var exampleTrimmedlastValue =  breakApart[breakApart.Length-1];
        var exampleReplace = example.Replace(exampleTrimmedlastValue,"NEW");
        var exampleTrimmed = exampleReplace pageid;
        Console.WriteLine("Original string:"  example);
        Console.WriteLine("Trimmed string:" exampleTrimmed); 
        }  
    }  
} 

but I don't find this very efficient and its huge can someone suggest any simpler way to do this

CodePudding user response:

Try this method. It will first find position of the string which you need to remove and if it finds it will remove it.

public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
        int place = Source.LastIndexOf(Find);

        if(place == -1)
           return Source;

        string result = Source.Remove(place, Find.Length).Insert(place, Replace);
        return result;
}

CodePudding user response:

Assuming the thing you want to find and replace is ALWAYS after a slash "/" and before "?id=", then you could just do:

string example = "https://something/ABCD/EFGH/IJKL/ABCD?id=1234567910";

string find = "ABCD";
string replaceWith = "NEW";
string exampleTrimmed = example.Replace("/"   find   "?id=", "/"   replaceWith   "?id=");

Console.WriteLine("Original string: "   example);
Console.WriteLine("Trimmed string: "  exampleTrimmed); 
  • Related