58

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 4

117

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"
Sign up to request clarification or add additional context in comments.

2 Comments

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.
The correct use is: string Text = "abc"; Text = Text.Insert(2,"XYZ");
42

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

That should work. I can't just go "temp = txtb.Text + ":" + txta.Text;" ?
Oh you certainly can. You just can't modify the original string.
@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.
You just can't modify the original string, but you can replace it. Replacing it feels just like modifying it most of the time.
>.> 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. >.>
7

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

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

1 Comment

The only performance efficient answer in this whole question!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.