简体   繁体   English

如何用string.Empty替换字符串中的隐藏(奇怪)字符

[英]How Replace Hidden (Strange) Characters From A String With string.Empty

please look at these codes : 请查看以下代码:

Health = HttpUtility.HtmlDecode(Health).Replace("%", string.Empty).Replace("\"", string.Empty).Replace("‭‎",string.Empty).Trim();
File.WriteAllText(@"d:\a.txt", Health);
char[] ar = Health.ToCharArray();
File.WriteAllText(@"d:\a.txt", string.Empty);
foreach (char a in ar)
{
    File.AppendAllText(@"d:\a.txt", a.ToString() + Environment.NewLine);
}

int a = int.Parse(Health); //-> I Always Have Error In This Line

the output of d:\\a.txt is like : d:\\a.txt的输出类似于:



1 1
0 0
0 0



there are 6 hidden and strange characters in that file and the Length of ar array is 9 . 该文件中有6个隐藏的奇怪字符, ar数组的长度为9
what are those hidden characters and how can i remove them? 这些隐藏的字符是什么,我该如何删除它们?
why Trim() couldn't remove those hidden characters? 为什么Trim()无法删除那些隐藏的字符?

Remove all non-printables: 删除所有不可打印的内容:

var str = "kljdfssdflksdfkl\x03kdkddk\x04lkdldök";
var onlyPrintableChars = str.Where(ch => !char.IsControl(ch)).ToArray();
var resultStr = new string(onlyPrintableChars);

Even if you remove the non-printable characters, your int.Parse could throw an exception if there are non-numeric characters in the string. 即使删除了不可打印的字符,如果字符串中包含非数字字符,您的int.Parse也可能会引发异常。 You probably want to use int.TryParse : 您可能要使用int.TryParse

int a;
if (!int.TryParse(Health, out a))
{
    // error: non-numeric
}

From the looks of things, you're trying to remove everything that isn't a digit (otherwise you wouldn't be doing an int.Parse on the result). 从外观上看,您正在尝试删除所有不是数字的东西(否则您将不会对结果进行int.Parse )。 If that's what you want to do, then you can write: 如果那是您想要做的,那么您可以编写:

Health = Regex.Replace(Health, "[^0-9]", "");

That's probably a bad idea, though, because it would turn "12foobar34" into "1234" . 但是,这可能不是一个好主意,因为它将把"12foobar34"变成"1234"

You probably should figure out what those bad characters are and how they're getting into your data. 您可能应该弄清楚那些坏字符是什么以及它们如何进入您的数据。 Then strip them from the input as soon as possible. 然后尽快从输入中删除它们。 Or, better yet, prevent them from getting there in the first place. 或者,更好的是,首先阻止他们到达那里。

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

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