Saranya
Saranya

Reputation: 1151

Replace multiple strings with a single sentence

Using ASP.Net and C#, how can I replace multiple string with a single one?

In my code, I use this loop to get the results, but the last argument is the only one filled.

    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;

Output:

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

How can I concatenate the multiple strings appropriately?

Upvotes: 0

Views: 529

Answers (5)

Richard Lang
Richard Lang

Reputation: 73

Would String.Join be something you're looking for? It will allow you to concat multiple strings with a specified separator.

Upvotes: 0

Daniel Simpkins
Daniel Simpkins

Reputation: 684

The code from the rest of these answers are good, but just a note. If you're replacing everything in one string with a for loop, then when you overwrite your BadCharacter values with the date, the iteration after that might replace the numbers in your date with the GoodCharacter value from your time variable. To get around this, I suggest changing the values for your BadCharacter array to something a bit more unique so you don't risk overwriting good values.

Upvotes: 0

Carra
Carra

Reputation: 17964

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

Replace it with this:

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

Upvotes: 1

qujck
qujck

Reputation: 14580

try assigning the result of each replacement to strReplaced

string strReplaced = desc;

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

Upvotes: 2

D Stanley
D Stanley

Reputation: 152566

You're overwriting strReplaced in each loop run. It seems like you want this instead:

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

Upvotes: 5

Related Questions