diff --git a/day9/case3.cpp b/day9/case3.cpp new file mode 100644 index 0000000..8b1f9c0 --- /dev/null +++ b/day9/case3.cpp @@ -0,0 +1,28 @@ +// 定义函数, 实现字符串的反转并输出 +// 例如: abcdefg -> gfedcba +#include + +using namespace std; + +void reverse(char str[], int len) +{ + int i = 0; // 为什么要从 0 开始? 因为字符串的第一个字符是 str[0] + int j = len - 1 - 1; // 为什么要再减 1? 因为字符串最后一个字符是 '\0' + for (; i < j; i++, j--) + { + str[i] = str[i] ^ str[j]; + str[j] = str[i] ^ str[j]; + str[i] = str[i] ^ str[j]; + } +} + +int main() +{ + char str[] = "abcdefg"; + int len = sizeof(str) / sizeof(str[0]); + cout << "原字符串: " << str << endl; + reverse(str, len); + cout << "反转后: " << str << endl; + + return 0; +} \ No newline at end of file