简体   繁体   中英

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 :



1
0
0



there are 6 hidden and strange characters in that file and the Length of ar array is 9 .
what are those hidden characters and how can i remove them?
why Trim() couldn't remove those hidden characters?

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. You probably want to use 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). 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" .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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