string.Equals判断为false,Trim无法移除隐藏字符该如何处理?
问题描述
我有两个字符串:
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
输出显示playerName末尾包含垂直制表符(字节11)和空格(字节32),但Trim()无法移除这些隐藏字符,该用什么方法处理?
解决方案
string.Trim()默认只移除空格、换行、回车、水平制表符等常规空白字符,垂直制表符(\v,ASCII 11)不在默认移除范围内,可通过以下方法解决:
方法1:自定义Trim字符集合
直接指定要移除的字符,将垂直制表符和常规空白字符一起传入Trim():
// 定义需要移除的空白字符集合 char[] charsToTrim = { ' ', '\t', '\v', '\n', '\r', '\f' }; bool areEqual = string.Equals(lp.Name.Trim(charsToTrim), playerName.Trim(charsToTrim));
方法2:正则表达式替换空白字符
用正则匹配所有Unicode空白字符(包含垂直制表符),可以选择移除首尾或全部空白:
using System.Text.RegularExpressions; // 移除字符串首尾的所有空白字符 string cleanedLpName = Regex.Replace(lp.Name, @"^\s+|\s+$", ""); string cleanedPlayerName = Regex.Replace(playerName, @"^\s+|\s+$", ""); // 或者移除字符串中所有空白字符(包括中间的) // string cleanedLpName = Regex.Replace(lp.Name, @"\s+", ""); // string cleanedPlayerName = Regex.Replace(playerName, @"\s+", ""); bool areEqual = string.Equals(cleanedLpName, cleanedPlayerName);
方法3:封装扩展方法(复用性更高)
如果需要频繁处理这类场景,可以封装一个扩展方法:
public static class StringExtensions { public static string TrimExtended(this string input) { if (string.IsNullOrEmpty(input)) return input; // 包含所有需要移除的空白字符 char[] charsToTrim = { ' ', '\t', '\v', '\n', '\r', '\f' }; return input.Trim(charsToTrim); } }
使用时直接调用:
bool areEqual = string.Equals(lp.Name.TrimExtended(), playerName.TrimExtended());
内容的提问来源于stack exchange,提问作者Flashheart
相关产品推荐
相关产品推荐

