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.
4 Answers
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"
2 Comments
Grungondola
You should probably note here that this does not actually insert this into the string that you are calling it on. The method returns another string with the specified text added at that index, but it does not modify the original string.
Paulo
The correct use is: string Text = "abc"; Text = Text.Insert(2,"XYZ");
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);
5 Comments
David Brewer
That should work. I can't just go "temp = txtb.Text + ":" + txta.Text;" ?
user541686
Oh you certainly can. You just can't modify the original string.
David Ly
@allthosemiles Yes that would work if you have 2 text boxes which it looks like you do. But then you're not really inserting a value into a string, you're just putting 2 string together with a
: in between. Mehrdad was assuming you only had one string that was 1012 and you wanted to make it 10:12. That's how I would've interpreted the question as well.aaaa bbbb
You just can't modify the original string, but you can replace it. Replacing it feels just like modifying it most of the time.
David Brewer
>.> That would make sense. My only reason for all this is to put it into a temp then use DateTime.ParseExact() being that temp is already setup correctly and the format is set right it should work but didn't. >.>
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 ) ;"
Comments
var sb = new StringBuilder();
sb.Append(beforeText);
sb.Insert(2, insertText);
afterText = sb.ToString();
1 Comment
Filip Vondrášek
The only performance efficient answer in this whole question!