C# Sharp Exercises: Insert a substring before the first occurrence of a string
C# Sharp String: Exercise-20 with Solution
Write a program in C# Sharp to insert a substring before the first occurrence of a string.
Sample Solution:-
C# Sharp Code:
using System;
public class Exercise20
{
public static void Main()
{
string str1;
string findstring;
string insertstring;
int i;
Console.Write("\n\nInsert a substing before the first occurence of a string :\n");
Console.Write("--------------------------------------------------------------\n");
Console.Write("Input the original string : ");
str1 = Console.ReadLine();
Console.Write("Input the string to be searched for : ");
findstring = Console.ReadLine();
Console.Write("Input the string to be inserted : ");
insertstring = Console.ReadLine();
i=str1.IndexOf(findstring); // locate the position of the first occurence of the string
insertstring = " " + insertstring.Trim() + " ";
str1 = str1.Insert(i, insertstring);
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 str
Flowchart:
C# Sharp Code Editor:
Contribute your code and comments through Disqus.
Previous: 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.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework