Hamed Kiani (Ph.D.)
  • Home
  • Publications
  • Contact

Reverse a c-string string (c++)

7/15/2015

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/******************************************************************************************
*******************************************************************************************
Chapter 1 Arrays and Strings

 * Reverse a c-string string.
 
By: Hamed Kiani (July 14, 2015)
******************************************************************************************
******************************************************************************************/

#include<iostream>

using namespace std;


// inplace reverse, time: O(n), space: O(1)
// Challenge: write this function using array instead of pointers. 

void reverse_str(char *str)
{
        char * tail = str;       
        while (*tail !='\0')
                tail++;
        tail--;
        char tmp;
        while(tail>str)
        {
                tmp = *str;
                *str++ = *tail;
                *tail-- = tmp;              
        }       
}

// Test it!
int main()
{
        char str[] = "Reverse this string!";        
        cout << "original str: " << str << endl;
        reverse_str(str);
        cout << "reversed str: " << str << endl;
        return 0;
}

Comments are closed.
    A place to practice the coding interview.

    Author

    Hamed Kiani

    Categories

    All
    Arrays And Strings
    Linked List
    Stack And Queue
    Trees And Graphs

    Archives

    September 2015
    July 2015

    RSS Feed

Copyright © 2020, Hamed Kiani