【问题标题】:Trim a string from a string从字符串中修剪字符串
【发布时间】:2021-04-04 05:55:29
【问题描述】:

因此,从字符串中修剪某些内容的正常方法是按字符修剪它。

例如:

string test = "Random Text";
string trimmedString = test.Trim(new Char[] { 'R', 'a', 'n'});
Console.WriteLine(trimmedString);
//the output would be "dom Text"

但不是这样做,有没有办法从字符串中完全删除组合字符“Ran”?

例如:

string test = "Random Text";
string trimmedString = test.Trim(string "Ran");
Console.WriteLine(trimmedString);
//the output would be "dom Text"

现在,上面的代码出错了,但是想知道这样的事情是否可能,谢谢!

【问题讨论】:

标签: c# string trim


【解决方案1】:

您可以像这样使用删除

string test = "Random Text";
string textToTrim = "Ran";

if (test.StartsWith(textToTrim))
    test = test.Remove(0, textToTrim.Length);
if (test.EndsWith(textToTrim))
    test = test.Remove(test.Length - textToTrim.Length);

【讨论】:

    【解决方案2】:

    您可以将字符串转换为字符数组,如下所示:

    string trimmedString = test.Trim("Ran".ToArray());
    

    但请注意,以这种方式修剪不会处理完全匹配(按字符顺序),因此如果您的 test"aRndom Text",它仍将被修剪为仅 "dom Text"

    如果你想通过精确匹配来修剪字符串,你可以使用如下代码:

    public static class TrimStringExtensions {
        public static string Trim(this string s, string toBeTrimmed){
             if(string.IsNullOrEmpty(toBeTrimmed)) return s;
             if(s.StartsWith(toBeTrimmed)){
                  s = s.Substring(toBeTrimmed.Length);
             }
             if(s.EndsWith(toBeTrimmed)){
                  s = s.Substring(0,s.Length - toBeTrimmed.Length);
             }
             return s;
        }
    }
    

    您也可以为此使用Regex

    public static class TrimStringExtensions {
         public static string Trim(this string s, string toBeTrimmed){
              if(string.IsNullOrEmpty(toBeTrimmed)) return s;
              var literal = Regex.Escape(toBeTrimmed);
              return Regex.Replace(s, $"^{literal}|{literal}$", "");
         }
    }
    

    使用它:

    string trimmedString = test.Trim("Ran");
    

    【讨论】:

      【解决方案3】:

      根据您的需要,我可以看到几种方法。

      A.你做什么,但更聪明一点

      string trimmedString = test.Trim("Ran".ToArray()); //Or TrimStart or TrimEnd
      

      B.替换

      string trimmedString = test.Replace("Ran", "");
      

      这将删除字符串中任何位置的“Ran”。

      C.仅替换第一次出现

      请参阅C# - Simplest way to remove first occurrence of a substring from another string

      D.正则表达式

      请看Remove a leading string using regular expression

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-26
        • 2012-03-21
        • 2014-11-27
        • 2022-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-17
        相关资源
        最近更新 更多