首页 > 解决方案 > 删除开始和结束之间的字符串的一部分

问题描述

先上代码:

   string myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>"
    // some code to handle myString and save it in myEditedString
    Console.WriteLine(myEditedString);
    //output now is: some question here regarding <at>disPossibleName</at>

我想<at>onePossibleName</at>从 myString 中删除。字符串onePossibleNamedisPossbileName可以是任何其他字符串。

到目前为止,我正在与

string myEditedString = string.Join(" ", myString.Split(' ').Skip(1));

这里的问题是 ifonePossibleName变成one Possible Name.

尝试myString.Remove(startIndex, count)也是如此 - 这不是解决方案。

标签: c#string

解决方案


根据您的需要,会有不同的方法,您可以使用 IndexOf 和 SubString,正则表达式也是一种解决方案。

// SubString and IndexOf method
// Usefull if you don't care of the word in the at tag, and you want to remove the first at tag
if (myString.Contains("</at>"))
{
    var myEditedString = myString.Substring(myString.IndexOf("</at>") + 5);
}
// Regex method
var stringToRemove = "onePossibleName";
var rgx = new Regex($"<at>{stringToRemove}</at>");
var myEditedString = rgx.Replace(myString, string.Empty, 1); // The 1 precise that only the first occurrence will be replaced

推荐阅读