Summary: in this tutorial, you will learn how to use the C# string Insert()
method to insert a string at a specified index position of a string.
Introduction to the C# String Insert() method
The C# string Insert()
method allows you to insert a string at a specified index position of a string and return a new string.
Here’s the syntax of the Insert()
method:
public string Insert (
int startIndex,
string value
);
Code language: C# (cs)
In this syntax:
startIndex
is the zero-based index position of the insertion.value
is the string to insert.
The Insert()
method doesn’t modify the current string but returns a new string with the value
inserted at the startIndex
of the current string.
If the startIndex
is equal to the length of the string, the Insert()
method appends the string value
to the end of the string.
If the startIndex
is zero, the Insert()
method prepends the string value
to the current string.
C# String Insert() method examples
Let’s take some examples of using the Insert()
method.
1) Using the string Insert() method to insert a space between two words in a string
The following example illustrates how to use the Insert()
method to insert a space between the word Hello
and World
:
var message = "HelloWorld!";
var startIndex = message.IndexOf("W");
var result = message.Insert(startIndex, " ");
Console.WriteLine(result);
Code language: C# (cs)
Output:
Hello World!
Code language: C# (cs)
How it works.
First, find the index of the "W"
in the message string by using the IndexOf()
method:
var startIndex = message.IndexOf("W");
Code language: C# (cs)
Second, insert the space at the found index into the string using the Insert()
method and assign the resulting string to the result
variable:
var result = message.Insert(startIndex, " ");
Code language: C# (cs)
Third, display the result string in the console:
Hello World!
Code language: C# (cs)
2) Using the string Insert() method to append a string to the current string
The following example illustrates how to use the Insert()
method to append the string "!"
to a string:
var message = "Hello World";
var result = message.Insert(message.Length, "!");
Console.WriteLine(result);
Code language: C# (cs)
Output:
Hello World!
Code language: C# (cs)
3) Using the string Insert() method to prepend a string
The following example shows how to use the Insert()
method to prepend a string to the current string:
var message = "Hello World!";
var result = message.Insert(0, "*");
Console.WriteLine(result);
Code language: C# (cs)
Output:
*Hello World!
Code language: C# (cs)
Summary
- Use the C# string
Insert()
method to insert a string into another string at a specified index.