[英]Replace multiple strings with a single sentence
使用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是否會是您要找的東西? 它將允許您使用指定的分隔符連接多個字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.