none
Blank Spaces in Char Array RRS feed

  • 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

    Tuesday, November 14, 2017 8:43 PM

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
    Tuesday, November 14, 2017 10:23 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
    Tuesday, November 14, 2017 10:23 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.

    Wednesday, November 15, 2017 2:51 AM
    Moderator
  • 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.
    Wednesday, November 15, 2017 3:17 AM
    Answerer