繁体   English   中英

在第n次出现令牌后插入字符串

[英]Insert into string after nth occurrence of token

我在字符串变量myHtml具有以下myHTML变量由某些函数填充的HTML,这些函数返回HTML,如下所示

string myHtml="<table> <tr id='12345'><td>Hello1</td></tr> <tr id='12346'><td>Hello2</td></tr> </table>";

在此示例中,返回的数据中有两行,我需要在上述行之间添加另一行,其中id=1234678 因此, myHtml可能看起来像

myHtml="<table> <tr id='12345'><td>Hello1</td></tr> <tr id='1234678'><td>Hello New</td></tr>  <tr id='12346'><td>Hello2</td></tr> </table>";

我想通过在字符串操作(例如indexOf等)的帮助下附加HTML来完成此操作,但是我不知道该怎么做。

不要为此使用字符串,而是为此使用一个库。 例如HTML敏捷包

总是只有两行吗? 如果是这样,它将起作用:

string newRow = " <tr id='1234678'><td>Hello New</td></tr> ";
int i = myHtml.IndexOf("</tr>") + 5;            
string newHtml = myHtml.Insert(i, newRow);

如果行数不限,我们将需要编写一种方法来查找要插入的特定索引。

例如:

    int IndexOfNth(string source, string token, int nTh)
    {
        int index = source.IndexOf(token);

        if (index != -1)
        {
            int i = 1;
            while (i++ < nTh)
                index = source.IndexOf(token, index + 1);
        }

        return index;
    }

然后,您将使用:

int i = IndexOfNth(myHtml, "</tr>", 1) + 5; // find first "</tr>" and insert after

// Or you could use
int i = IndexOfNth(myHtml, "<tr ", 2); // find second "<tr " and insert before

尝试这个

    myHtml = "<table> <tr id='12345'><td>Hello1</td></tr> <tr id='12346'><td>Hello2</td></tr> </table>";
    int index1 = myHtml.IndexOf("<tr", 0);
    int index2 = myHtml.IndexOf("<tr", index1 + 3); // 3 for amount of characters in '<tr'
    myHtml = myHtml.Insert(index2, "<tr id='1234678'><td>Hello</td></tr>");

您还可以通过循环来构建数组,以便在现有行多于两个的情况下,将行插入到任意位置。

尝试使用Linq到XML。 根据您的字符串创建一个XDocument。 然后搜索您的tr节点并插入新的tr节点。

var newTR = new XElement("tr", new XAttribute("id", "1234678"), new XElement("td", "Hello3"));
TextReader tr = new StringReader(myHtml);
XDocument doc = XDocument.Load(tr);
doc.Decendants().Skip(1).AddAfterSelf(newTR);
var newStr = doc.ToString();

暂无
暂无

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

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