C# - Add A Substring Before The First Occurrence Of A String
Maybe your like
Last update on January 14 2026 12:30:42 (UTC/GMT +8 hours)
Write a program in C# Sharp to insert a substring before the first occurrence of a string.
Sample Solution:-
C# Sharp Code:
using System; // Define the Exercise20 class public class Exercise20 { // Main method - entry point of the program public static void Main() { // Declare variables to store user input and index string str1; string findstring; string insertstring; int i; // Prompt the user to input the original string Console.Write("\n\nInsert a substring before the first occurrence of a string :\n"); Console.Write("--------------------------------------------------------------\n"); Console.Write("Input the original string : "); str1 = Console.ReadLine(); // Prompt the user to input the string to be searched for Console.Write("Input the string to be searched for : "); findstring = Console.ReadLine(); // Prompt the user to input the string to be inserted Console.Write("Input the string to be inserted : "); insertstring = Console.ReadLine(); // Locate the position of the first occurrence of the string to be found i = str1.IndexOf(findstring); // Modify the insert string for formatting purposes insertstring = " " + insertstring.Trim() + " "; // Insert the insert string before the first occurrence of the found string str1 = str1.Insert(i, insertstring); // Display the modified string Console.Write("The modified string is : {0}\n\n", str1); } }Sample Output:
Insert a substing before the first occurence of a string : -------------------------------------------------------------- Input the original string : The string is str Input the string to be searched for : string Input the string to be inserted : original The modified string is : The original string is strFlowchart:
Go to:
- C# Sharp String Exercises Home ↩
- C# Sharp Programming Exercises Home ↩
PREV : Write a program in C# Sharp to find the number of times a substring appears in the given string. NEXT : Write a C# Sharp program to compare (less than, greater than, equal to ) two substrings.
C# Sharp Code Editor:
Click to Open Editor
Contribute your code and comments through Disqus.
Tag » Add Character To String C Sharp
-
C# Adding A Character In A String - Stack Overflow
-
Add Character To String C# Code Example - Code Grepper
-
String.Insert(Int32, String) Method (System) - Microsoft Docs
-
Append A Char To End Of A String In C# | Techie Delight
-
C# - How To Append A Char To A String - 1400+ .NET C# Examples
-
C# Add Strings - ZetCode
-
6 Effective Ways To Concatenate Strings In C# - C# Corner
-
How To Append A Character To A String In C - GeeksforGeeks
-
How To Insert One String Into Another Using Insert() In C#
-
C# Strings - TutorialsTeacher
-
How Do I Add A Char To A String? - Unity Forum
-
2.9. Inserting Text Into A String - C# Cookbook [Book] - O'Reilly
-
C# String Append (Add Strings) - Dot Net Perls
-
C# Strings - W3Schools