Skip to content

Instantly share code, notes, and snippets.

@xun-gong
Last active August 29, 2015 14:02
Show Gist options
  • Save xun-gong/c7e705a292d725cf98d4 to your computer and use it in GitHub Desktop.
Save xun-gong/c7e705a292d725cf98d4 to your computer and use it in GitHub Desktop.
CareerCup1.2.cpp
/* Chapter 1
* 1.2 Implement function void reverse(char* str) in C or C++ which reverses a null-terminated string.
*/
#include <iostream>
#include <string>
using namespace std;
// Approach 1:
// Copy paste manipulation, not utilize the pointer in C++
// Doesn't change original string
void reverse_brute(char* str)
{
int length = strlen(str);
// check empty string
if (length == 0) {
cout << "The string length is 0" << endl;
return;
}
char reverse_version[length+1];
for (int i = 0; i < length; i++) {
reverse_version[i] = str[length-1-i];
}
reverse_version[length] = '\0';
cout << "Output from called function: " << reverse_version << endl;
}
// Approach 2:
// Utilize pointers to manipulate with string
// Swap char within string
void swap(char* a, char* b)
{
char tmp[] = " ";
*tmp = *a;
*a = *b;
*b = *tmp;
}
// My reverse implementation
void reverse(char* str)
{
int length = strlen(str);
if (length == 0) {
cout << "The string length is 0" << endl;
return;
}
int i = 0;
while (i < length/2) {
swap(str+i, str+length-1-i);
i++;
}
}
// The most elegant way to solve this problem
void reverse_elegant(char* str)
{
char* begin = str;
char* end = str;
// Move pointer end to the last non-terminal position
while(*end != '\0'){
end++;
}
end--;
// No need to know length
// Pointer manipulation within str
while (begin < end ) {
swap(begin, end);
begin++;
end--;
}
}
int main()
{
char test[] = "fdaDFAq4565$#&$5_5fdsllie";
// char test2[] = ""; // For test empty string
reverse_elegant(test);
cout << test << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment