Skip to content

Instantly share code, notes, and snippets.

@habina
Last active February 28, 2022 14:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save habina/d55da65182a6622e64b5 to your computer and use it in GitHub Desktop.
Save habina/d55da65182a6622e64b5 to your computer and use it in GitHub Desktop.
1.2 Implement a function void reverse(char* str) in C or C++ which reverses a null-terminated string.
#include <stdio.h>
void swap(char* a, char* b);
void reverse(char* str);
int main(){
char strArray[] = "1point3acres";
printf("Before Reverse: %s\n", strArray);
reverse(strArray);
printf("After Reverse: %s\n", strArray);
}
void swap(char* a, char* b){
char c = *a;
*a = *b;
*b = c;
}
void reverse(char* str) {
// handle the special case when it is an empty string
if (!*str) {
return;
}
// mark down the begin of the string
char* begin = str;
// pointing to the last character
char* end = begin + strlen(str) - 1;
// swap begin and end
while (begin < end) {
swap(begin, end);
begin++;
end--;
}
}
@ZhuGuanyu
Copy link

差点忘掉还可以用 strlen() 这个函数来写 计算字符串长度的。。。。哎, 我是多久没有写代码了。。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment