用一句话替换多个字符串

本文关键字:字符串 替换 一句话 | 更新日期: 2023-09-27 18:24:19

使用ASP.Net和C#,如何用单个字符串替换多个字符串?

在我的代码中,我使用这个循环来获得结果,但最后一个参数是唯一填充的参数。

    public void smssend(string CustomerName,string from,string to,string date,string time)
    {
        con.Open();
        string str1 = "select * from Master ";
        SqlCommand command1 = new SqlCommand(str1, con);
        SqlDataReader reader1 = command1.ExecuteReader();
        while (reader1.Read())
        {
            Label1.Text = reader1["Template"].ToString();
        }
        reader1.Close();
        string desc = Label1.Text;
        string[] BadCharacters = { "1", "2", "3", "4","5" };
        string[] GoodCharacters = { CustomerName, from, to, date,time };
        string strReplaced = "";
        int i;
        for(i=0; i<=4; i++)
        {
            strReplaced = desc.Replace(BadCharacters[i], GoodCharacters[i]);
        }
        Label1.Text = strReplaced;

输出:

1 and 2 and 3 and 4 and 12:00:00

如何适当地连接多个字符串?

用一句话替换多个字符串

在每次循环运行中都会覆盖strReplaced。你似乎想要这个:

    for(i=0; i<=4; i++)
    {
        desc = desc.Replace(BadCharacters[i], GoodCharacters[i]);
    }
    Label1.Text = desc;

尝试将每次替换的结果分配给strReplaced

string strReplaced = desc;
int i;
for(i=0; i<=4; i++)
{
    strReplaced = strReplaced.Replace(BadCharacters[i], GoodCharacters[i]);
}
Label1.Text = strReplaced;
int i;
for(i=0; i<=4; i++)
{
   strReplaced = **desc**.Replace(BadCharacters[i], GoodCharacters[i]);
}

替换为:

int i;
var strReplaced  = desc;
for(i=0; i<=4; i++)
{
  strReplaced = **strReplaced**.Replace(BadCharacters[i], GoodCharacters[i]);
}

其余答案的代码都很好,但只是一个注释。如果用for循环替换一个字符串中的所有内容,那么当用日期覆盖BadCharacter值时,之后的迭代可能会用时间变量中的GoodCharacter值替换日期中的数字。为了解决这个问题,我建议将BadCharacter数组的值更改为更独特的值,这样就不会有覆盖好值的风险。

String.Join会是您想要的东西吗?它将允许您使用指定的分隔符连接多个字符串。