定义函数, 实现字符串的反转并输出

This commit is contained in:
flykhan 2023-06-25 16:03:32 +08:00
parent f3750b2851
commit 782d75d3b1
1 changed files with 28 additions and 0 deletions

28
day9/case3.cpp Normal file
View File

@ -0,0 +1,28 @@
// 定义函数, 实现字符串的反转并输出
// 例如: abcdefg -> gfedcba
#include <iostream>
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;
}