首页 > 其他分享 >字符串逆序(多种解法)

字符串逆序(多种解法)

时间:2022-11-06 11:31:26浏览次数:59  
标签:arr reverse string int char str 字符串 解法 逆序

1:>

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include <string.h>
void reverse_string(char arr[])
{
int l = 0;
int r = strlen(arr) - 1;
while (l < r)
{
char tmp = arr[l];
arr[l] = arr[r];
arr[r] = tmp;
l++;
r--;
}
}
int main()
{
char arr[] = { "abcdef" };
reverse_string(arr);//arr是数组名,数组名是首元素的地址
printf("%s\n", arr);//fedcba
return 0;
}

2:>

#include <stdio.h>
#include <string.h>
void reverse_string(char*str)
{
int l = 0;
int r = strlen(str) - 1;
while (l < r)
{
char tmp = *(str + l);
*(str + l) = *(str + r);
*(str + r) = tmp;
l++;
r--;
}
}
int main()
{
char arr[] = { "abcdef" };
reverse_string(arr);
printf("%s",arr);
return 0;
}

3:>

#include <stdio.h>
int Strlen(char* str)
{
int count = 0;
while (*str != '\0')
{
count++;
str++;
}
return count;
}
void reverse_string(char*str)
{
int l = 0;
int r = Strlen(str) - 1;
while (l < r)
{
char tmp = *(str + l);
*(str + l) = *(str + r);
*(str + r) = tmp;
l++;
r--;
}
}
int main()
{
char arr[] = { "abcdef" };
reverse_string(arr);
printf("%s",arr);
return 0;
}

4:>

#include <stdio.h>
int Strlen(char* str)
{
int count = 0;
while (*str != '\0')
{
count++;
str++;
}
return count;
}
void reverse_string(char* str)
{
int len = Strlen(str);
char tmp = *str;
*str = *(str + len - 1);
*(str + len - 1) = '\0';
if (Strlen(str + 1) >= 2)
reverse_string(str + 1);
*(str + len - 1) = tmp;
}
int main()
{
char arr[] = { "abcdef" };
reverse_string(arr);
printf("%s", arr);
return 0;
}

标签:arr,reverse,string,int,char,str,字符串,解法,逆序
From: https://blog.51cto.com/u_15501985/5827250

相关文章