首页 > 解决方案 > 从字符串中修剪字符串

问题描述

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

例如:

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#stringtrim

解决方案


您可以像这样使用删除

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

推荐阅读