Q:

Write a program in C# Sharp to insert a substring before the first occurrence of a string

0

Write a program in C# Sharp to insert a substring before the first occurrence of a string.
Test Data :
Input the original string : this is a string
Input the string to be searched for : a
Input the string to be inserted : test
Expected Output :

The modified string is : this is  test a string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now