在指定字符串后添加字符串

Put*_*aKg 2 c# string

假设我有以下 HTML 字符串

<head>

</head>

<body>
<img src="stickman.gif" width="24" height="39" alt="Stickman">
<a href="http://www.w3schools.com">W3Schools</a>
</body> 
Run Code Online (Sandbox Code Playgroud)

我想在<head>标签之间添加一个字符串。所以最终的 HTML 字符串变成

<head>
<base href="http://www.w3schools.com/images/">
</head>

<body>
<img src="stickman.gif" width="24" height="39" alt="Stickman">
<a href="http://www.w3schools.com">W3Schools</a>
</body> 
Run Code Online (Sandbox Code Playgroud)

所以我必须搜索第一次出现的<head>字符串,然后在后面插入<base href="http://www.w3schools.com/images/">

我如何在 C# 中做到这一点。

dav*_*v_i 6

那么为什么不做一些简单的事情,比如

myHtmlString.Replace("<head>", "<head><base href=\"http://www.w3schools.com/images/\">");
Run Code Online (Sandbox Code Playgroud)

不是最优雅或可扩展的,但满足您的问题的条件。


gza*_*axx 5

另一种方法是这样做:

string html = "<head></head><body><img src=\"stickman.gif\" width=\"24\" height=\"39\" alt=\"Stickman\"><a href=\"http://www.w3schools.com\">W3Schools</a></body>";
var index = html.IndexOf("<head>");

if (index >= 0)
{
     html = html.Insert(index + "<head>".Length, "<base href=\"http://www.w3schools.com/images/\">");
}
Run Code Online (Sandbox Code Playgroud)