Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert value into a string at a certain position?

Tags:

string

c#

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.

like image 256
David Brewer Avatar asked Jan 28 '11 21:01

David Brewer


People also ask

How do you insert a character in a string at a certain position?

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.

How do you add a string to a specific position in Python?

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.

How do you add a string to the middle of a string in Python?

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.


3 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"
like image 154
andersh Avatar answered Oct 22 '22 14:10

andersh


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);
like image 40
user541686 Avatar answered Oct 22 '22 14:10

user541686


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 ) ;"
like image 7
Andy Avatar answered Oct 22 '22 12:10

Andy