简体   繁体   English

使用C#将所有特殊字符(包括空格)替换为-

[英]Replace all Special Characters including space with - using C#

I want to replace all Special Characters which can't be parse in URL including space, double space or any big space with '-' using C#. 我想使用C#将所有无法在URL解析的Special Characters包括空格,双倍空格或任何大空格)替换为'-'。

I don't want to use any Parse Method like System.Web.HttpUtility.UrlEncode . 我不想使用任何System.Web.HttpUtility.UrlEncode类的解析方法。

How to do this ? 这个怎么做 ? I want to include any number of space between two words with just one '-'. 我想在两个单词之间仅用一个“-”包括任意数量的空格。

For example, if string is Hello# , how are you? 例如,如果string为Hello# , how are you?
Then, Result should be, Hello-how-are-you , no '-' if last index is any special character or space. 然后,如果最后一个索引是任何特殊字符或空格,则Result应该是Hello-how-are-you ,而不是'-'。

 string str = "Hello# , how are you?";
 string newstr = "";
 //Checks for last character is special charact
 var regexItem = new Regex("[^a-zA-Z0-9_.]+");
 //remove last character if its special
 if (regexItem.IsMatch(str[str.Length - 1].ToString()))
 {
   newstr =   str.Remove(str.Length - 1);            
 }
 string replacestr = Regex.Replace(newstr, "[^a-zA-Z0-9_]+", "-");

INPUT: Hello# , how are you? 输入:您好#,您好吗?

OUTPUT: Hello-how-are-you 输出:你好,你好吗

EDIT: Wrap it inside a class 编辑:将其包装在类中

   public static class StringCheck
        {
            public  static string Checker()
            {
                string str = "Hello# , how are you?";
                string newstr = null;
                var regexItem = new Regex("[^a-zA-Z0-9_.]+");
                if (regexItem.IsMatch(str[str.Length - 1].ToString()))
                {
                    newstr = str.Remove(str.Length - 1);
                }
                string replacestr = Regex.Replace(newstr, "[^a-zA-Z0-9_]+", "-");
                return replacestr;
            }

        }

and call like this, 像这样打电话

 string Result = StringCheck.Checker();
string[] arr1 = new string[] { " ", "@", "&" };

newString = oldString;
foreach repl in arr1
{
    newString= newString.Replace(repl, "-");
}

Of course you can add into an array all of your spec characters, and looping trough that, not only the " ". 当然,您可以将所有规范字符添加到数组中,并循环通过,而不只是“”。

More about the replace method at the following link 有关以下链接的替换方法的更多信息

You need two steps to remove last special character and to replace all the remaining one or more special characters with _ 您需要两个步骤来删除最后一个特殊字符,并用_替换所有剩余的一个或多个特殊字符。

public static void Main()
{
  string str = "Hello# , how are you?";
  string remove = Regex.Replace(str, @"[\W_]$", "");
  string result = Regex.Replace(remove, @"[\W_]+", "-");
  Console.WriteLine(result);
  Console.ReadLine();
}

IDEONE IDEONE

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

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