C/C++中利用指針實現字符串的反轉

在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

因此這篇利用指針基本實現了字符串的反轉。如果有錯誤的地方歡迎大家批評指正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章