C語言 --- 實現字符串反轉

方法一:通過開闢與源字符串一樣大小的內存實現反轉

#include <stdio.h>
#include <string.h>

void test01()
{
	int count = 0;
	char src[] = "hello,world";
	char *dest = NULL;
	int len = strlen(src);

	dest = (char*)malloc(len *sizeof(char));
	memset(dest, 0, sizeof(len*sizeof(char)));

	char *d = dest;
	//char *s = src + len - 1;
	char *s = (char*)(&src + 1) - 2 ;		//上面注視的代碼也可以實現功能,這裏的代碼也可以用
	//這裏爲什麼要減2,因爲字符數組的最後一個元素爲'\0',所以要多減1

	while (len-- != 0)
	{
		*d++ = *s--;
	}
	*d = '\0';
	printf("%s\n", dest);
}


int main(void)
{
	test01();

	system("pause");
	return 0;
}

上面一種方法需要額外的內存,若源字符串太長,則導致空間複雜度大

 

方法二:不需要額外開闢內存

#include <stdio.h>

void Flip(char*array, int len) {
	int left = 0;
	int right = len;
	while (left <= right) {
		char tmp = array[left];//數組內容進行翻轉
		array[left] = array[right];
		array[right] = tmp;
		left++;//對循環條件進行調整
		right--;//對循環條件進行調整
	}
}

int main() {
	char array[] = "hello world";
	int len = strlen(array) - 1;//取長度注意是取下標最後一位
	Flip(array, len);
	for (int i = 0; i <= len; ++i) {
		printf("%c", array[i]);
	}
	printf("\n");
	system("pause");
	return 0;
}

 

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