从字符串中修剪字符串

时间:2021-04-04 05:55:29

标签: c# string trim

所以从字符串中修剪某些东西的正常方法是通过字符修剪它。

例如:

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"

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

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

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

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

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

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

答案 2 :(得分:0)

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

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