【问题标题】:How to replace string with the value of variable in c#?如何用c#中的变量值替换字符串?
【发布时间】:2025-12-13 09:55:02
【问题描述】:
if(Node.NodeType.ToString().Equals("Element", StringComparison.InvariantCultureIgnoreCase))
{
    if(Node.Name.ToString().Equals("DeployWebsite", StringComparison.InvariantCultureIgnoreCase))
    {
        Count++;
    }
    string myString = Count.ToString();
    string name = "//"+"website"+"["+ myString+"]"+"/";

    string[] DetailsOfNodesToDisplay = Node.InnerText.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

    for(int i = 0; i < DetailsOfNodesToDisplay.Count(); i++)
    {
        string addressOfNode = DetailsOfNodesToDisplay[i].Replace('.', '/');
        if(Node.Name.ToString().Equals("DeployWebsite", StringComparison.InvariantCultureIgnoreCase))
        {
            addressOfNode = addressOfNode.Replace("/Website/", "name");
            // string addressOfNode1 = addressOfNode.Replace("/website/", "//website[1]/");
        }
    }
}

我想用name 变量的值替换"/Website"。 名称变量是包含值的字符串。

【问题讨论】:

  • 我已添加代码快照,请查看
  • 如果你能提供minimal reproducible example(文本),那就太棒了。
  • 请在问题中粘贴代码,而不是屏幕截图的链接。使用addressOfNode.Replace("/Website/", name)"name" 是字符串,name 是变量
  • 请注意,"//"+"website"+"[" 也可能不是您想要写的

标签: c# asp.net c#-4.0 c#-3.0 csharpcodeprovider


【解决方案1】:

如果您在运行时创建字符串,请使用字符串插值,例如

string someString = "someText/{name}"; Where "/{name}" was "/Website" before.

但如果字符串已经定义,则使用

someString.Replace("/Website", name);

【讨论】: