Answer:
The program in csharp is given below.
using System;
class Test
{
//variables required to hold the strings and index
static string line;
static string test;
static int idx;
static string final="";
static string replace_at_index(string str, int index, string s)
{
//replacement string inserted at the required position
final = line.Insert(idx, test);
//extra characters removed
final = final.Remove(idx+test.Length, test.Length);
return final;
}
static void Main()
{
Console.WriteLine("Enter a sentence");
line = Console.ReadLine();
Console.WriteLine("Enter the index to replace the string");
idx = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the replacement string");
test = Console.ReadLine();
//the resultant string displayed
Console.WriteLine("The string after replacement is "+ replace_at_index(line, idx, test));
}
}
OUTPUT
Enter a sentence
i am working now.
Enter the index to replace the string
3
Enter the replacement string
not
The string after replacement is i anotorking now.
Step-by-step explanation:
1. Declare the variables to hold the user inputted strings, the index and the resultant string.
2. The variables are declared outside Main() and hence declared as static.
3. Inside Main(), user input is taken for the original string, the index to be replaced and the new replacement string.
4. Define the method, replace_at_index() that takes all the three user entered values as parameters and return the resultant string.
5. Inside replace_at_index() method, the replacement string is inserted into the original string at the required position using insert() method.
6. The resultant string is stored in the variable, final.
7. After insert(), remove() method removes the original character(s) which got shifted after the insert() operation.
8. The replace_at_index() method returns the resultant string having the replaced string inserted in the original string.
9. The whole code is written inside class as csharp is purely object-oriented language.
10. No object of any class is created since only a single class is involved.
11. The string operations have been done using the in-built string functions of csharp language.
12. The index of the string begins with 0 hence the string operations work accordingly.