Home
Map
String Insert ExamplesUse the Insert method to add a substring to an existing string at an index.
C#
This page was last reviewed on Nov 8, 2023.
Insert. This C# method places one string into another. This forms a new string. We use Insert() to place one substring in the middle of a string—or at any other position.
String Remove
Method notes. We can add one string at any index into another. IndexOf returns a target index. Insert can be used to concatenate strings—it can be used for a prepend operation.
String IndexOf
string.Concat
First example. Let us use Insert(). In programs, we will have strings that are dynamic and not string literals. But we will often need to insert literals into them.
Start We start with a string that reads "a b." At index 2, we insert a new substring with the value of "xy."
So Our result string contains the value "a xy b." We can still use all the original strings in the program if we need them.
using System; string value = "a b"; // Insert string at index 2. string adjusted = value.Insert(2, "xy "); Console.WriteLine("INSERT RESULT: " + adjusted);
INSERT RESULT: a xy b
Insert, IndexOf example. Often we need to insert a string at a position relative to some existing characters in the string. We can use the result of IndexOf to call the Insert() method.
Here We find the position of the comma in the string with IndexOf, and then Insert() a new string 2 characters after it.
using System; string value = "cat, frog"; // Find the comma. int position = value.IndexOf(", "); // Make sure we have a comma. if (position >= 0) { // Insert a string 2 places after the comma. string adjusted = value.Insert(position + 2, "green "); Console.WriteLine("END: " + adjusted); }
END: cat, green frog
ArgumentNullException. We cannot pass a null string to the Insert() method. This causes an exception. Make sure to prevent null strings from reaching the point where you call Insert.
null
null String
ArgumentException
class Program { static void Main() { string value = "test"; string result = value.Insert(0, null); } }
Unhandled Exception: System.ArgumentNullException: Value cannot be null. Parameter name: value at System.String.Insert(Int32 startIndex, String value) at Program.Main()....
Benchmark, Insert. Suppose we need to put a new string at index 0 (at the start) of a string. We can use the string concat operator, or use the Insert method.
Here We benchmark the Insert method with an index of 0, against a string "prepend" operation with the plus operator.
Version 1 This calls Insert to insert 2 strings at index 0. It makes sure the result is correct.
Version 2 This uses string.Concat (the plus operator) to prepend strings. It also ensures it comes up with the correct result.
Result In .NET 7 for Linux (as of 2023) the string.Concat method has been optimized, so it is faster.
using System; using System.Diagnostics; const int _max = 10000000; string beforePart = 5.ToString(); string afterPart = 10000.ToString(); // Version 1: use Insert at position 0. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { string result = afterPart.Insert(0, beforePart); result = result.Insert(0, "X"); if (result != "X510000") { break; } } s1.Stop(); // Version 2: use concat to add new prefix. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { string result = beforePart + afterPart; result = "X" + result; if (result != "X510000") { break; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
46.70 ns Insert(0) 43.45 ns + (Concat)
A warning. On invalid arguments, Insert() raises ArgumentNullException and ArgumentOutOfRangeException. We must not send Insert() a null string or an index that is not present.
Exception
With Insert, we inserted a substring into the middle of an existing string. Insert() is useful here. Insert can also be used to prepend one string to another.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 8, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.