How to get rid of empty characters from the string?
I am reading the location for a file from local HDD which is dynamically created from a local host. I have managed to read the output from batch file but the issue is when i am reading for the location it is also including special characters I want to get rid of these character.
So far I have tried following approaches: -> converting string to character array, eaxtracting only the LettersAndNumbers with '.' and '_' symbols -> splitting string: path.Split (spC, 7,StringSplitOptions.RemoveEmptyEntries); -> trying to read from lsat of the string till '/' and then reversing the extracted char array and copying it to string.
But nothing seems to work here....
Please help me out here ;'(
You can see the invalid character is not showing up in debug log. Further you can see the upload_randomstring.jpg and then __ends in the new line that is the split string. I wouldn't have got to know what this evil character (%00%) if not for Uri.EscapeUriString(...) class.
add for www:file:///C:/Users/shubh/AppData/Local/Temp/upload_c33e4a116d8034a032f8a251d7ea5656.jpg%00%00%00%00%00%00%00
What I find weird here is, that I am using the following debug command: UnityEngine.Debug.Log ("before check: "+path+"__ends");
but notice that the output omits the "__ends" string. Which I am not able to comprehend why?
Answer by enigmatic · Dec 28, 2016 at 12:08 PM
Finally got it working, but I still don't get it why my previous code wasn't working for omitting the special character.
Here is how I was doing it before:
char[] fnca = fileName.ToCharArray ();
char[] validC = new char[50];
int vc = 0;
for (int i = 0; i < fnca.Length; i++) {
if (Char.IsLetterOrDigit (fnca [i]) || fnca [i] == '_' || fnca [i] == '.') {
//UnityEngine.Debug.Log (fnca [i]);
validC [vc] = fnca [i];
vc++;
if (fnca [i] == '.') {
validC [vc] = 'j';vc++;validC [vc] = 'p';vc++;validC [vc] = 'g';vc++;
i = fnca.Length + 2;
}
}
else
UnityEngine.Debug.Log ("Invalid char: " + fnca [i]);
}
validC [vc] = '\0';
fileNameNew = new string (validC);
Later I used stringbuilder class for formatting the string and this worked:
string RemoveSpecialCharacters(string str) {
StringBuilder sb = new StringBuilder();
foreach (char c in str) {
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_' || c=='\\' || c==':') {
sb.Append(c);
}
}
return sb.ToString();
}
Some peace. Would still appreciate if anyone could find the underlying issue here.