TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Insert String Examples

Use the Insert method to add a substring to an existing string at an index.
Insert. This 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.StringsRemove
Notes, insert. 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.IndexOfstring.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.

String: We start with a string that reads "bird, frog." At index 6, we insert a new substring with the value of "green."

So: Our result string contains the value "bird, green frog." We can still use all the original strings in the program if we need them.

C# program that uses Insert using System; class Program { static void Main() { string value = "bird, frog"; // Insert string at index 6. string adjusted = value.Insert(6, "green "); Console.WriteLine("FINAL RESULT: " + adjusted); } } Output FINAL RESULT: bird, green frog
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.

C# program that uses Insert, IndexOf using System; class Program { static void Main() { 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); } } } Output 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.NullNull StringsArgumentException
C# program that causes null error class Program { static void Main() { string value = "test"; string result = value.Insert(0, null); } } Output 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: Using Insert at index 0 is a better choice, but the performance difference is small.

Tip: There is probably no performance reason to prefer Insert over concat. But insert() might be clearer for this use.

C# program that benchmarks Insert, string.Concat using System; using System.Diagnostics; class Program { const int _max = 10000000; static void Main() { 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")); } } Output 47.61 ns Insert(0) 50.30 ns + (Concat)
Internals. The Insert method goes directly to an internal, unmanaged code implementation. This means it is highly optimized and avoids some overhead of you doing it in your own code.

Note: On invalid arguments, the Insert method raises ArgumentNullExceptions and ArgumentOutOfRangeExceptions.

So: We must not send Insert() negative indexes, a null string, or an index that is not present in the current string.

A summary. 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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf