1

有人可以帮助建议我如何创建一个函数,如果它出现在 C# 中的字符串末尾,它将修剪掉一些文本。我所拥有的是一些以以下结尾的字符串:

<p>&nbsp;</p>

所以例如var a = "sometext<p>&nbsp;</p>";

我知道我可以用text.EndsWith("<p>&nbsp;</p>")它来检测它是否匹配,但是我怎么能删除它呢?

4

5 回答 5

4

你可以使用正则表达式

Regex.Replace(text, "<p>&nbsp;</p>$", "")

这样,您不必检查.EndsWith("<p>&nbsp;</p>")

于 2013-10-14T11:46:31.567 回答
3

假设您只想在标签结束时删除标签,请使用:

text.Substring(0, text.Length - "<p>&nbsp;</p>".Length);
于 2013-10-14T11:43:22.940 回答
2

我会使用 LastIndexOf 和 Substring:

string toReplace = "<p>&nbsp;</p>";
if(a.EndsWith(toReplace)) a.Substring(0, a.LastIndexOf(toReplace));
于 2013-10-14T11:43:49.203 回答
1

尝试这个:

RemoveFromEndIfContains("<p>&nbsp;</p>");


function string RemoveFromEndIfContains(string text, string remove)
{
if (text.EndsWith())
  return text.Substring(0, text.Length - remove.Length);
else
  return text;
}
于 2013-10-14T11:49:58.603 回答
1
text.Remove(text.Length - "<p>&nbsp;</p>".Length);

从此字符串中删除从指定位置开始并持续到最后一个位置的所有字符。

于 2013-10-14T11:55:00.803 回答