String Problems: Reverse A String and Remove Characters From A String (C# Solution)
Problem 1 Description: Reverse a string such that “a cat has paws” becomes “paws has cat a”.
Problem 2 Description: Remove a set of characters from a given string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringManipulationProblems
{
class Program
{
const string DEFAULT_COMMAND = "ReverseString";
const string DEFAULT_ARGUMENT_1 = "messages that have been in Spam more than 30 days will be automatically deleted";
const string DEFAULT_ARGUMENT_2 = "aioeu";
static void Main(string[] args)
{
string commandName;
string commandArg1;
string commandArg2;
if (args.Length < 1)
{
commandName = DEFAULT_COMMAND;
commandArg1 = DEFAULT_ARGUMENT_1;
commandArg2 = DEFAULT_ARGUMENT_2;
}
else if (args.Length == 1)
{
commandName = args[0];
commandArg1 = DEFAULT_ARGUMENT_1;
commandArg2 = "aioeu";
}
else if (args.Length == 2)
{
commandName = args[0];
commandArg1 = args[1];
commandArg2 = "aioeu";
}
else
{
commandName = args[0];
commandArg1 = args[1];
commandArg2 = args[2];
}
string result = String.Empty;
StringPuzzles puzzles = new StringPuzzles();
switch (commandName)
{
case "ReverseString":
if (commandArg1.Equals(DEFAULT_ARGUMENT_1))
{
Console.Out.Write("No string argument provided. Using default string: ");
Console.WriteLine(DEFAULT_ARGUMENT_1);
}
Console.Out.WriteLine("About to call method " + commandName);
result = puzzles.ReverseString(commandArg1);
break;
case "RemoveChars":
if (commandArg1.Equals(DEFAULT_ARGUMENT_1))
{
Console.Out.Write("No string argument provided. Using default string: ");
Console.WriteLine(DEFAULT_ARGUMENT_1);
}
Console.Out.WriteLine("About to call method " + commandName);
result = puzzles.RemoveChars(commandArg1, commandArg2);
break;
default:
Console.Out.WriteLine("Incorrect command! Please try again.");
break;
}
Console.Out.WriteLine("The original string was:");
Console.Out.WriteLine(commandArg1);
Console.Out.WriteLine("The modified string is:");
Console.Out.WriteLine(result);
Console.Out.WriteLine("Please press ENTER to continue...");
Console.In.ReadLine();
}
}
class StringPuzzles
{
public string ReverseString(string inputString)
{
List<string> wordList;
StringBuilder reversedString = new StringBuilder();
wordList = new List<string>(inputString.Split(' '));
for (int i = wordList.Count - 1; i >= 0; i--)
{
reversedString.Append(wordList[i] + " ");
}
return reversedString.ToString();
}
public string RemoveChars(string str, string remove)
{
List<char> toDelete = new List</char><char>();
StringBuilder deletedStr = new StringBuilder();
// Create a list of characters to delete from string
toDelete.AddRange(remove.ToCharArray());
// Create string with specified characters removed
foreach (char c in str.ToCharArray())
{
if (!(toDelete.Contains(c)))
{
deletedStr.Append(c);
}
}
return deletedStr.ToString();
}
}
}