David Brewer
David Brewer

Reputation: 1974

Insert value into a string at a certain position?

i'm looking to place a value from a text box lets say "12" to a certain place in a string temp variable. Then I want to place another value after that say "10" but with a : in between like a time. Both come from Text boxes and are validated so they can only be numbers.

Upvotes: 56

Views: 164755

Answers (4)

andersh
andersh

Reputation: 8383

If you just want to insert a value at a certain position in a string, you can use the String.Insert method:

public string Insert(int startIndex, string value)

Example:

"abc".Insert(2, "XYZ") == "abXYZc"

Upvotes: 115

kid
kid

Reputation: 309

var sb = new StringBuilder();
sb.Append(beforeText);
sb.Insert(2, insertText);
afterText = sb.ToString();

Upvotes: 4

Andy
Andy

Reputation: 187

If you have a string and you know the index you want to put the two variables in the string you can use:

string temp = temp.Substring(0,index) + textbox1.Text + ":" + textbox2.Text +temp.Substring(index);

But if it is a simple line you can use it this way:

string temp = string.Format("your text goes here {0} rest of the text goes here : {1} , textBox1.Text , textBox2.Text ) ;"

Upvotes: 7

user541686
user541686

Reputation: 210785

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

Upvotes: 42

Related Questions