C# String.Insert() Method with Example

In this tutorial, we will learn about the String.Insert() method with its usage, syntax, and examples. By IncludeHelp Last updated : April 07, 2023

C# String.Insert() Method

The String.Insert() method is used to insert a string in an existence string at specified index and returns a new string.

Syntax

public string String.Insert(int index, string value);

The method is called with "this" string i.e. the string in which we have to insert the string.

Parameter(s)

  • index – represents the index/position of the current string where new string value to be inserted.
  • value – a new string to be inserted.

Return Value

string – it returns a new string containing the inserted string at given index.

Input/Output Example

Input:
string str = "IncludeHelp";
string str1 = " programming ";
    
Function call
str.Insert(7, str1);

Output:
Include programming Help

C# String.Insert() Method Example 1

using System;

class IncludeHelp {
  static void Main() {
    // declaring string variables
    string str = "IncludeHelp";

    // inserting space between Include and Help
    string new_string = str.Insert(7, " ");

    Console.WriteLine("str: " + str);
    Console.WriteLine("new_string: " + new_string);
  }
}

Output

str: IncludeHelp
new_string: Include Help

C# String.Insert() Method Example 2

using System;

class IncludeHelp {
  static void Main() {
    // declaring string variables
    string str = "IncludeHelp";
    string str1 = " programming ";

    // inserting str1 after "Include"
    string new_string = str.Insert(7, str1);

    Console.WriteLine("str: " + str);
    Console.WriteLine("new_string: " + new_string);
  }
}

Output

str: IncludeHelp
new_string: Include programming Help




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.