-2

String reverse which contains spaces and special characters. How can I achieve this without using regex?

Input: "M @#.AD()/A?#M"

Output :"MADAM"

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • 10
    What have you tried, and what is not working? – Maksim Simkin Jul 24 '19 at 09:29
  • can you use another string? – Or Yaacov Jul 24 '19 at 09:29
  • This seems like a very good use case for regular expressions - why don't you want to use them? – Diado Jul 24 '19 at 09:30
  • 1
    First you need to remove the special characters from the string, check this : https://stackoverflow.com/questions/1120198/most-efficient-way-to-remove-special-characters-from-string. then reverse is, check this : https://stackoverflow.com/questions/228038/best-way-to-reverse-a-string – Hamza Jul 24 '19 at 09:34
  • Welcome to Stack Overflow. Could you clarify the requirements? It doesn't look like this is string *reversal* - it's just filtering out certain characters. If you want reversal as well, I would separate the two steps - filter first, then reverse. – Jon Skeet Jul 24 '19 at 09:37
  • 6
    As a side note: Using a palindrome for a reversing question is slightly confusing. – Freggar Jul 24 '19 at 09:38

3 Answers3

4

Here's a one-liner:

string.Join("", input.Where(char.IsLetter).Reverse()));
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
1

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);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

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".

Popa611
  • 121
  • 2
  • 10