String reverse which contains spaces and special characters. How can I achieve this without using regex?
Input: "M @#.AD()/A?#M"
Output :"MADAM"
String reverse which contains spaces and special characters. How can I achieve this without using regex?
Input: "M @#.AD()/A?#M"
Output :"MADAM"
Here's a one-liner:
string.Join("", input.Where(char.IsLetter).Reverse()));
This code should work fine:
string n = "M @#.AD()/A?#M";
string tmp = Regex.Replace(n, "[^0-9a-zA-Z]+", "");
string backwards = new string(tmp.Reverse().ToArray());
Console.WriteLine(backwards);
Removing everything except the string(words).
"[^0-9a-zA-Z]+"
Here is the second version, but in my opinion you should use Regex for this case.
You can save the special characters in a string array and ask if they exist in the string with Contains
.
Code:
string n = "M @#.AD()/A?#M";
string[] chars = new string[] {"?", " ", ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", "\"", ";", "_", "(", ")", ":", "|", "[", "]" };
//Iterate the number of times based on the String array length.
for (int i = 0; i < chars.Length; i++)
{
if (n.Contains(chars[i]))
{
n = n.Replace(chars[i], "");
}
}
// To reverse the string
string backwards = new string(n.Reverse().ToArray());
Console.WriteLine(backwards);
One of the solutions that came to my mind:
string input = "D @#.O()/?#G";
StringBuilder builder = new StringBuilder();
for (int i = input.Length-1; i >= 0; i--)
{
if (Char.IsLetter(input[i]))
{
builder.Append(input[i]);
}
}
string result = builder.ToString();
Result is "GOD".