首页 > 解决方案 > 如何替换字符串中的子字符串,并获取包含替换子字符串的完整字符串?

问题描述

如何替换字符串中的子字符串,并获取包含替换子字符串的完整字符串?

string ex1 = "Example1";
string output;

for (int i = 0; i <= ex1.Lenght; i++)
{

    if (ex1.Substring(i, 1).Contains("1")
    {

        output = ex1.Substring(i, 1).Replace("1", "!");
    } // output is here ! but i want the complete string with the Replaced substring, like "Example!"
}

Console.WriteLine(output);

标签: c#stringreplacesubstring

解决方案


String.Replace自己做你想要的 - 不需要子字符串:

string output = ex1.Replace("1", "!");

推荐阅读