【问题标题】:remove specific text from middle of string (only first occurrence from end of a string)从字符串中间删除特定文本(仅从字符串末尾第一次出现)
【发布时间】:2021-11-18 13:04:19
【问题描述】:

我需要从字符串中间删除一个特定值,并且只从字符串末尾删除它的第一次出现,例如

网址:https://something/ABCD/EFGH/IJKL/**ABCD**?id=1234567910

在上面的 url 字符串中,我需要将最后一个“ABCD”替换为“NEW”,如下所示:

网址:https://something/ABCD/EFGH/IJKL/**NEW**?id=1234567910

目前我的做法是

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); 
        }  
    }  
} 

但我觉得这不是很有效,而且它的巨大有人可以提出任何更简单的方法来做到这一点

【问题讨论】:

标签: c# .net string


【解决方案1】:

试试这个方法。它会首先找到您需要删除的字符串的位置,如果找到它将删除它。

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;
}

【讨论】:

    【解决方案2】:

    假设你要查找和替换的东西总是在斜杠“/”之后和“?id=”之前,那么你可以这样做:

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

    【讨论】:

      【解决方案3】:

      在查看了您的所有建议后,我添加了以下代码以实现我想要的解决方案。

      using System;  
        
      namespace StringReplaceSample  
      {  
         public class Program  
          {  
              public static void Main(string[] args)  
              {  
              string example = "https://something/ABCD/EFGH/IJKL/ABCD?id=1234567910";
              string replaceValue = "ABCD";
              int lastIndex = example.LastIndexOf(replaceValue, StringComparison.InvariantCulture);
              example = example.Remove(lastIndex, replaceValue.Length).Insert(lastIndex, "NEW");        
              Console.WriteLine("Original string:" +example); 
              }  
          }  
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多