在C/C++中字符串是以指针的形式存储的,因此可以利用指针来进行反转。
下面我用代码来进行演示。
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
void revstring(char *test)
{
int length = strlen(test);
int step = length - 1;
char *s1 = test;
char *s2 = test + step;
char temp;
while (s1 < s2)
{
temp = *s1;
*s1 = *s2;
*s2 = temp;
*s1++;
*s2--;
}
}
int main()
{
char a[] = "abcde";
revstring(a);
std::cout << a << endl;
}
输出为
edcba
因此这篇利用指针基本实现了字符串的反转。如果有错误的地方欢迎大家批评指正。