Reverse a C-Style String

Description

Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)


Tips:

A C-Style String will always have a null character at the end of the string which you can not see, but it’s actually there. So in the case of “abcd”, strlen() will return 4, which indicates the length of the string itself, while sizeof() will return 5, the extra one space is for the \0 known as null character.

Pseudo-code

1
2
3
4
for(from 0 to the middle position of the string)
{
  switch the current character with the corresponding character at the other side of the string;
}

My C++ Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 Time complexity: O(n/2)
 Space: O(1)
*/
void reverse(char *s)
{
    if (NULL == s) return;
    size_t len = strlen(s);
    for (int n = 0; n < len / 2; n++)
    {
        char temp = s[len - n - 1];
        s[len - n - 1] = s[n];
        s[n] = temp;
    }
}

My Objective-C Solution

Test the Solution

1
2
3
4
5
6
7
int main()
{
    char s[] = "switch the current character with the corresponding character at the other side of the string";
    reverse(s);
    cout<<s<<endl;
    return 0;
}

Comments