toad
toad

Reputation: 57

code does not insert all elements of array to string

i have this code which should insert all elements of array which is some html on random places in a string. but it only inserts last element to that string. please help

Random insertPos = new Random();
int pos = insertPos.Next(txtInput.Text.Length);
int firSpace= txtInput.Text.IndexOf(" ", pos);
int secSpace = txtInput.Text.IndexOf(" ", firSpace+1);
int wLen = secSpace - firSpace;<br/>
string word = txtInput.Text.Substring(firSpace,wLen);
foreach (string url in urlArray)
{
    txtOutput.Text = 
         txtInput.Text.Replace(word, "<a href=\"" + url + "\">" + word + "</a>");
}

Upvotes: 2

Views: 250

Answers (4)

Branimir
Branimir

Reputation: 4397

As Jaison said you are using = instead of +=, but there are better solutions. Remember that strings are immutable. Use string.Format or StringBuilder where you're concatenating strings. Examples:

string[] strArray = {"a", "b", "c"};
string word = "word";

//1st solution +=
string output = "";

foreach (string str in strArray)
    output += "<a href=\"" + str + "\">" + word + "</a>";

Console.WriteLine(output);

//better solution string.Format
output = "";

foreach (string str in strArray)            
    output += string.Format("<a href=\"{0}\">{1}</a>", str, word);

Console.WriteLine(output);

//StringBuilder
StringBuilder sb = new StringBuilder();

foreach (string str in strArray)            
    sb.AppendFormat("<a href=\"{0}\">{1}</a>", str, word);

output = sb.ToString();

Console.WriteLine(output);

//linq & string.Join
output = string.Join("", strArray.Select( str => string.Format("<a href=\"{0}\">{1}</a>", str, word)).ToArray());

Console.WriteLine(output);

Console.Read();

Upvotes: 0

Karl Knechtel
Karl Knechtel

Reputation: 61654

You are repeatedly saying "figure out what happens when I insert the HTML into txtInput 's text, and assign the result to the txtOutput text". But this does not actually change the text in txtInput, so you are starting fresh each time; and you throw away the txtOutput text each time to replace it with the new stuff.

Upvotes: 1

MatthiasG
MatthiasG

Reputation: 4532

You overwrite the Text property of the textbox in every step of the foreach loop. Only the result of last loop will be left.

Upvotes: 1

jason
jason

Reputation: 241789

You are replacing (=) the contents of txtOutput.Text on every iteration so of course you are only going to see the last result. Consider using +=1 first to get it working and then a StringBuilder if your performance is suffering and this is a bottleneck.

1: It's not clear exactly how you want it formatted, but at least += will append and assign the result of the append instead of just the result of the current iteration.

Upvotes: 2

Related Questions