如何在c#中进行字符串比较时处理%20

pat*_*tel 6 c# string

我试图比较两个字符串,但其中一个字符串末尾包含一个空格.我使用了Trim()并进行了比较,但是没有工作,因为白色空间正在转换为%20,而我的东西Trim并没有删除它.它是像"abc""abc%20",我能在这样的情况做比较whih太忽略大小写字符串?

Sha*_*ard 5

使用 HttpUtility.UrlDecode 解码字符串:

string s1 = "abc ";
string s2 = "abc%20";
if (System.Web.HttpUtility.UrlDecode(s1).Equals(System.Web.HttpUtility.UrlDecode(s2)))
{
    //equals...
}
Run Code Online (Sandbox Code Playgroud)

对于 WinForms 或 Console(或任何非 ASP.NET)项目,您必须在项目中添加对System.Web程序集的引用。


Joa*_*son 5

%20 是url编码的空间版本.

你不能直接使用它去除它Trim(),但是你可以使用HttpUtility.UrlDecode()来解码%20回到一个空格,然后完全修剪/完成比较;

using System.Web;

//...

var test1 = "HELLO%20";
var test2 = "hello";

Console.WriteLine(HttpUtility.UrlDecode(test1).Trim().
           Equals(HttpUtility.UrlDecode(test2).Trim(),              
           StringComparison.InvariantCultureIgnoreCase));

> true
Run Code Online (Sandbox Code Playgroud)