在C#中将一些字符串注入字符串的特定部分

Ste*_*Pet 5 c# string string-concatenation

如何将一些字符串插入另一个字符串的特定部分.我想要实现的是我的变量中有一个像这样的html字符串string stringContent;

 <html><head>
 <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
 <meta name="Viewport" content="width=320; user-scaleable=no; 
 initial-scale=1.0">
 <style type="text/css"> 
 body {
       background: black;
       color: #80c0c0; 
 } 
 </style>
 <script>

</script>
</head>
<body>
<button type="button" onclick="callNative();">Call to Native 
Code!</button>

<br><br>
</body></html>
Run Code Online (Sandbox Code Playgroud)

我需要在<script> <script/>标签内添加以下字符串内容

    function callNative()
{
    window.external.notify("Uulalaa!");
}
    function addToBody(text)
{
    document.body.innerHTML = document.body.innerHTML + "<br>" + text;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在C#中实现这一目标.

Jam*_*ess 6

假设您的内容存储在字符串中content,您可以首先找到脚本标记:

int scriptpos = content.IndexOf("<script");
Run Code Online (Sandbox Code Playgroud)

然后超过脚本标记的结尾:

scriptpos = content.IndexOf(">", scriptpos) + 1;
Run Code Online (Sandbox Code Playgroud)

最后插入新内容:

content = content.Insert(scriptpos, newContent);
Run Code Online (Sandbox Code Playgroud)

这至少允许脚本标记中的潜在属性.

  • 你不应该忘记字符串在C#中是不可变的,而`content.Insert`不会修改内容,所以你必须用新值重新赋值. (3认同)