简体   繁体   English

如何反转包含空格和特殊字符的字符串

[英]How can I reverse string which contains spaces and special characters

String reverse which contains spaces and special characters.包含空格和特殊字符的字符串反向。 How can I achieve this without using regex?如何在不使用正则表达式的情况下实现这一目标?

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

Output : "MADAM"输出: "MADAM"

这是一个单行:

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.这是第二个版本,但我认为您应该在这种情况下使用 Regex。

You can save the special characters in a string array and ask if they exist in the string with Contains .您可以将特殊字符保存在字符串数组中,并使用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".结果是“上帝”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM