Saturday, October 3, 2015

[1.2] reverse a C-style string

1. Example

Reverse left most and right most SWAP and left most++ and right most --

C-style string is a NULL-terminated sequence of characters stored in a C++ array. ASCII 0 designates the NULL character. A string literal, which is a sequence of characters enclosed in double quotes, is a C-style string

char str[] = "A String";
 The string is stored in memory as a 9 element character array.
 A S t r i n g  NULL
  |
str

char *s1 = "hi lol";
char s2[] = "hi haha";
*s1      =>  'h';
*s1++ =>   'i';
*s1++ =>   ' ';

2. Implementation


void reverse (char *str)
{
     
    char *end = str; // a new pointer point to str
    char tmp;
    if ( str )
    {
         // 1. Get the right most char
         while (*end)
            ++end;
         --end; // back one char from last '0' char

         // 2. Get the left most char , str It is
        
         // 3. Start Swapping
         while ( str < end  )
         {
              tmp = *str;        // left most to tmp
              *str++ = *end;     // left most and right most SWAP and left most ++
              *end-- = tmp;      // right most assign and right most --
         }
         
    }
}
3. Similar Ones

No comments:

Post a Comment