string.Equals 计算结果为 false

问题描述 投票:0回答:1

我有两根弦:

  • lp.Name

    从类中包含的后端服务器数据库返回的字符串

    LocalPlayer

    public class LocalPlayer
    {
         public string Name;
    }
    
  • playerName

    本地字符串变量。

这是我正在运行的代码块:

private void UpdatePlayer()
{
    bool localPlayerFound = false;

    if (player != null)
    {
        if (player.localPlayers != null)
        {
            if (player.localPlayers.Count > 0)
            {
                foreach (LocalPlayer lp in player.localPlayers)
                {

                   Debug.Log("Name =" + lp.Name + " Length " + lp.Name.Length + " Bytes " + string.Join(",", System.Text.Encoding.Unicode.GetBytes(lp.Name)));
                   Debug.Log("Name =" + playerName + " Length " + playerName.Length + " Bytes " + string.Join(",", System.Text.Encoding.Unicode.GetBytes(playerName)));

                    bool areEqual = string.Equals(lp.Name.Trim(), playerName.Trim());

                    Debug.Log(areEqual);

                    if (areEqual)
                    {
                        localPlayerFound = true;
                        // Fill out Player stats
                    }
                }
            }
        }
    }
    if (localPlayerFound == false) // NO players yet in Local Database - Create a new one
    {
        AddNewLocalPlayer();
    }
}

调试语句的输出是:

经过一些建议后,我将长度和编码添加到调试语句中。这是调试语句中出现的内容。

Name =Flash Length 5 Bytes 70,0,108,0,97,0,115,0,104,0


Name =Flash​ Length 6 Bytes 70,0,108,0,97,0,115,0,104,0,11,32


False


如果修剪不能删除隐藏字符,我可以使用什么?

输出确认字节 11 对应于垂直制表符,字节 32 对应于空格字符。

谢谢

c# string string-comparison
1个回答
0
投票

如果修剪不能删除隐藏字符,我可以使用什么?

也许使用正则表达式可以提供高度可定制的后备选项。

using System.Text;
using System.Text.RegularExpressions;

Console.Title = "Try Regex";

string flash1 = Encoding.Unicode.GetString(new byte[]{ 70, 0, 108, 0, 97, 0, 115, 0, 104, 0 });
string flash2 = Encoding.Unicode.GetString(new byte[] { 70, 0, 108, 0, 97, 0, 115, 0, 104, 0, 11, 32 });

Console.WriteLine($"{flash1} {flash2}");
Console.WriteLine(string.Equals(flash1, flash2));
Console.WriteLine();

flash1 = flash1.ToSafeCompare();
flash2 = flash2.ToSafeCompare();

Console.WriteLine($"{flash1} {flash2}");
Console.WriteLine(string.Equals(flash1, flash2));


Console.ReadKey();

static partial class Extensions
{
    public static string ToSafeCompare(this string input) =>
        Regex.Replace(input, "[^a-zA-Z0-9]", "");
}

© www.soinside.com 2019 - 2024. All rights reserved.