How To Insert One String Into Another Using Insert() In C#

ExploreEXPLORE THE CATALOGSupercharge your career with 700+ hands-on coursesView All CoursesPythonJavaJavaScriptCReactDockerVue JSRWeb DevDevOpsAWSC#LEARNING TOOLSExplore the industry's most complete learning platformCoursesLevel up your skillsSkill PathsAchieve learning goalsProjectsBuild real-world applicationsMock InterviewsNewAI-Powered interviewsPersonalized PathsGet the right resources for your goalsLEARN TO CODECheck out our beginner friendly courses.PricingFor BusinessResourcesNewsletterCurated insights on AI, Cloud & System DesignBlogFor developers, By developersFree CheatsheetsDownload handy guides for tech topicsAnswersTrusted answers to developer questionsGamesSharpen your skills with daily challengesSearchCoursesLog InJoin for freeHow to insert one string into another using Insert() in C#

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 classclass 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); }}Run

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#.

Relevant Answers

Explore Courses

Free Resources

License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)

Tag » Add Character To String C Sharp