请看一下这些代码:
\n\nstring str_to_find = "\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\\r\\n";\nstring str = "Nancy" + str_to_find;\nif (str.EndsWith(str_to_find)) {\n str = Remove_Last_String(str, str_to_find);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这是方法:
\n\npublic static string Remove_Last_String(string Source, string Find) {\n int i = Source.LastIndexOf(Find);\n if (i >= 0) {\n string new_str = Source.Substring(0, i);\n return new_str;\n }\n else return Source;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我想要Nancy输出。
\n但是方法返回:
\n Nancy\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96\xe2\x9e\x96
\n这些奇怪的字符有什么问题&我该如何修复它?
你弄乱了不寻常的 Unicode 字符。或者也许他们在逗你。请始终指定字符串比较样式。在您的代码中使用它:
int i = Source.LastIndexOf(Find, StringComparison.Ordinal);
强制StringComparison.Ordinal字符串比较忽略当前区域性设置。显然,文化设置使算法的行为与您/我们想要/期望的不同。