From 782d75d3b1557f5d13b273cb47bc377e3ddcf980 Mon Sep 17 00:00:00 2001 From: flykhan Date: Sun, 25 Jun 2023 16:03:32 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9A=E4=B9=89=E5=87=BD=E6=95=B0,=20?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=9A=84=E5=8F=8D?= =?UTF-8?q?=E8=BD=AC=E5=B9=B6=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day9/case3.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 day9/case3.cpp 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