简体   繁体   English

我该如何移除 <p></p> 从C#中的字符串末尾开始(如果存在)?

[英]How can I remove <p>&nbsp;</p> from the end of a string in C# if it's present there?

Can someone help suggest how I can create a function that will trim off some text if it appears at the end of a string in C#. 有人可以帮我建议一下,如果它出现在C#字符串的末尾时,我该如何创建一个可以剪裁一些文本的函数。 What I have is some strings that end with: 我有一些以结尾的字符串:

<p>&nbsp;</p>

So for example var a = "sometext<p>&nbsp;</p>"; 因此,例如var a = "sometext<p>&nbsp;</p>";

I know that I can use text.EndsWith("<p>&nbsp;</p>") to detect if it matches but then how could I remove that? 我知道我可以使用text.EndsWith("<p>&nbsp;</p>")来检测它是否匹配,但是如何删除它呢?

You could use a regular expression 您可以使用正则表达式

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

This way, you don't have to check .EndsWith("<p>&nbsp;</p>") 这样,您不必检查.EndsWith("<p>&nbsp;</p>")

假设您只想删除标记,如果标记位于标记的结尾,请使用:

text.Substring(0, text.Length - "<p>&nbsp;</p>".Length);

I would use LastIndexOf and Substring: 我将使用LastIndexOf和Substring:

string toReplace = "<p>&nbsp;</p>";
if(a.EndsWith(toReplace)) a.Substring(0, a.LastIndexOf(toReplace));

try this: 尝试这个:

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;
}
text.Remove(text.Length - "<p>&nbsp;</p>".Length);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM