Last active
February 28, 2022 14:58
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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--; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
差点忘掉还可以用 strlen() 这个函数来写 计算字符串长度的。。。。哎, 我是多久没有写代码了。。