C语言—字符串逆序

时间:2024-03-05 18:34:14
#include <stdio.h>
#include <string.h>

//字符串逆序放置
int main()
{
	char ch[] = "abcdef";
	int i = 0;
	int j = 0;
	char a;
	printf("%s\n",ch);
	//字符串个数
	j = strlen(ch) - 1;
	//j = sizeof(ch) / sizeof(ch[0]) - 2;
	while(i < j ){
		a = ch[i];
		ch[i] = ch[j];
		ch[j] = a;
		i++;	
		j--;	
	}
	printf("%s\n",ch);
	return 0;
}

        函数方式实现:

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

void reverse(char ch[])
{
	int i = 0;
	int j = strlen(ch) - 1;
	char a;
	while(i < j ){
		a = ch[i];
		ch[i] = ch[j];
		ch[j] = a;
		i++;	
		j--;	
	}
}
//字符串逆序放置
int main()
{
	char ch[] = "abcdef";
	printf("%s\n",ch);
	reverse(ch);
	printf("%s\n",ch);
	return 0;
}

        在函数内部就不能使用sizeof来求字符串长度了,字符数组传递的也是地址。

        递归函数实现: 

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

void reverse(int left,int right,char ch[])
{
	char a;
	if(left < right)
	{
		a = ch[left];
		ch[left] = ch[right];
		ch[right] = a;
		left++;
		right--;
		reverse(left,right,ch);
	}
}
//字符串逆序放置
int main()
{
	char ch[] = "abcdefg";
	int left = 0;
	int right = 0;
	printf("%s\n",ch);
	right = sizeof(ch) / sizeof(ch[0]) - 2;//字符串个数
	reverse(left,right,ch);
	printf("%s\n",ch);
	return 0;
}

         递归函数实现:(只有一个参数)

#include <stdio.h>

int my_strlen(char* ch)
{
	int count = 0;
	while(*ch != '\0')
	{
		count++;
		ch++;
	}
	return count;
}
//只有一个参数的递归
void reverse(char* str)
{
	char temp = *str;
	int len = my_strlen(str);
	*str = *(str + len - 1);
	*(str + len - 1) = '\0';
	if(strlen(str + 1) >= 2)
		reverse(str + 1);
	*(str + len - 1) = temp;
}
//字符串逆序放置
int main()
{
	char ch[] = "abcdefg";
	printf("%s\n",ch);
	reverse(ch);
	printf("%s\n",ch);
	return 0;
}