Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
communitycreator

How to insert one string into another using Insert() in C#

Theodore Kelechukwu Onyejiaku

Overview

In C#, the Insert() method takes a string and inserts it into another string. Insert() accepts the index position to start the insertion from, inserts the second string at the index position of the first string, and then returns the modified string.

Syntax

public string Insert(int32 first, String second)

Parameters

  • first: The index position to start the insertion at.
  • second: The string we want to insert into another.

Return value

The Insert method returns a modified string.

Code example

The example below demonstrates the use of the Insert method to insert a string into another string.

// create our class
class StringInserter
{
    // main method
    static void Main()
    {
      // create strings to insert to
      string str1 = "Hlo";
      string str2 = "ld";

      // insert strings to the string above
      string modStr1 = str1.Insert(1, "el");
      string modStr2 = str2.Insert(0, "wor");

      // print returned modified strings
      System.Console.WriteLine(modStr1);
      System.Console.WriteLine(modStr2);
    }
}

In the code above, we insert "el" to "Hlo", starting from the second position, to form "Hello". We also insert "wor" to "ld", thus modifying it to "world". This is the use of the Insert() method in C#.

RELATED TAGS

c#
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring