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.
One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer. Syntax: str.
If you need to insert a given char at multiple locations, always consider creating a list of substrings and then use . join() instead of + for string concatenation. This is because, since Python str are mutable, + string concatenation always adds an aditional overhead.
In the example above, I used the index value to 'slice' the string in to 2 substrings: 1 containing the substring before the insertion index, and the other containing the rest. Then I simply add the desired string between the two and voilà, we have inserted a string inside another.
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"
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);
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 ) ;"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With