Using visual studio (C#) create a program, name it PRGYOURNAMEFA1, that implements a search and replace function recursively. Your program should allow a user to enter a string , a substring to be replaced in the entered string and a character/s to replace the found substring
Program Structure
1. A main class that implements the logic of the program – name this class TestSearchReplace
2. Add a class named SearchReplace to the main class with two methods, including:
a. SearchSubstring()- return method
b. ReplaceSubString() - void method
The two method should be called using an object in the main class. DONT CREATE THE TWO METHODS IN THE MAIN CLASS
using System;
using System.IO;
using System.Collections.Generic;
namespace App
{
class TestSearchReplace
{
class SearchReplace
{
public int SearchSubstring(string message, string subString)
{
int messageSize = message.Length;
int subStringSize = subString.Length;
if (messageSize == 0 || messageSize < subStringSize)
{
return 0;
}
if (message.Substring(0, subStringSize).Equals(subString))
{
return SearchSubstring(message.Substring(subStringSize - 1), subString) + 1;
}
return SearchSubstring(message.Substring(subStringSize - 1), subString);
}
public void ReplaceSubString(ref string message, string subString, string characterReplace)
{
if (message.Contains(subString))
{
message=message.Replace(subString, characterReplace);
ReplaceSubString(ref message, subString, characterReplace);
}
}
}
static void Main(string[] args)
{
Console.Write("Enter string: ");
string message = Console.ReadLine();
Console.Write("Enter substring: ");
string subString = Console.ReadLine();
Console.Write("Enter a new string to replace: ");
string characterReplace = Console.ReadLine();
SearchReplace SearchReplace = new SearchReplace();
int n=SearchReplace.SearchSubstring(message, subString);
if (n > 0)
{
Console.WriteLine("\nA new string after replacing: ");
SearchReplace.ReplaceSubString(ref message, subString, characterReplace);
Console.WriteLine(message);
}
else {
Console.WriteLine("\nSubstring does not exist.");
}
Console.ReadLine();
}
}
}
Comments
Leave a comment