Answered by:
Blank Spaces in Char Array

Question
-
When I run below code, why are spaces output at the beginning?
string str1 = "this is a string";
char[] newchar = new char[str1.Length];str1.CopyTo(0, newchar, 0, str1.Length);Array.Sort(newchar);for (int i=0; i<newchar.Length;i++){Console.Write(newchar[i]);}Console.ReadKey();
CG
Answers
-
Because there's a space between "this" and "is", another space between "is" and "a", and and a third space between "a" and "string".
And when you sort the array, spaces come before letters.
- Proposed as answer by cheong00Editor Wednesday, November 15, 2017 3:14 AM
- Marked as answer by cheong00Editor Thursday, November 23, 2017 1:52 PM
All replies
-
Because there's a space between "this" and "is", another space between "is" and "a", and and a third space between "a" and "string".
And when you sort the array, spaces come before letters.
- Proposed as answer by cheong00Editor Wednesday, November 15, 2017 3:14 AM
- Marked as answer by cheong00Editor Thursday, November 23, 2017 1:52 PM
-
Hello CG,
If you don't want the whitespaces occurs , just edit some code as below.
string str1 = "this is a string"; str1=str1.Replace(" ",""); char[] newchar = new char[str1.Length]; ...
Sincerely,
Neil Hu
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com. -
Or to answer the "why" part, take a look at the ASCII table and see what is the numeric value of "Space" and other characters.
- Edited by cheong00Editor Wednesday, November 15, 2017 3:18 AM