在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
因此這篇利用指針基本實現了字符串的反轉。如果有錯誤的地方歡迎大家批評指正。