当前位置:网站首页>C语言逆序打印字符串的两种方法
C语言逆序打印字符串的两种方法
2022-07-25 22:24:00 【高邮吴少】
非递归
非递归的思路比较巧妙,如下图:
我们把第一个和倒数第一个交换,把第二个和倒数第二个交换,把第三个和倒数第三个交换…
你可能会问:“如果我字符串的字符数是奇数怎么办?”
回答是,中间那个字符和他自己交换,没啥影响,他还是他那个位置。
void reverse_string(char* str)
{
int len = strlen(str);
char* left=str;
char* right = str + len - 1;
while (left < right)
{
char tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
int main()
{
char arr[20] = {
0 };
printf("请输入你想逆序的字符串:");
scanf("%s", arr);
reverse_string(arr);
printf("%s", arr);
return 0;
}

递归
递归的思路很简单,就是一层一层往下“递”,直到字符串变成只有一个字符,然后打印那个字符
随后就是一层一层往上“归”,打印指针锁定的那个字符即可
void reverse_string(char* str)
{
if (*str != '\0')
{
reverse_string(str + 1);
}
printf("%c", *str);
}
int main()
{
char arr[20] = {
0 };
printf("请输入你想逆序的字符串:");
scanf("%s", arr);
reverse_string(arr);
return 0;
}

边栏推荐
- 3dslicer introduction and installation tutorial
- Data governance under data platform
- 核电站在席卷欧洲的热浪中努力保持安全工作
- Flex layout
- Why is the integer type 128 to byte -128
- Title: give a group of arrays, arranged from large to small and from small to large.
- Compile and decompile
- What is the difference between minor GC and full GC?
- What is class loading? Class loading process?
- Why does redisv6.0 introduce multithreading?
猜你喜欢

Advanced database · how to add random data for data that are not in all user data - Dragonfly Q system users without avatars how to add avatar data - elegant grass technology KIR

IPv4 addresses have been completely exhausted, and the Internet can work normally. NAT is the greatest contributor!

JMeter websocket interface test

编译和反编译

xxl-job中 关于所有日志系统的源码的解读(一行一行源码解读)

Xiaobai programmer's seventh day

After 2 years of functional testing, I feel like I can't do anything. Where should I go in 2022?

According to the use and configuration of data permissions in the open source framework

QML module not found

Xiaobai programmer the next day
随机推荐
Formal parameters, arguments and return values in functions
Wechat applet (anti shake, throttling), which solves the problem that users keep pulling down refresh requests or clicking buttons to submit information; Get the list information and refresh the data
internship:普通常用的工具类编写
TS:typora代码片段缩进显示异常(已解决)-2022.7.24
JS interview questions
Leetcode 106. construct binary tree from middle order and post order traversal sequence
3day
The testing work is not valued. Have you changed your position?
Gan, why '𠮷 𠮷'.Length== 3 ??
xxl-job中 关于所有日志系统的源码的解读(一行一行源码解读)
Div drag effect
平台架构搭建
[assembly language 01] basic knowledge
Having met a tester with three years' experience in Tencent, I saw the real test ceiling
synchronized与volatile
Don't know mock test yet? An article to familiarize you with mock
Imitation Tiktok homepage interface
Wechat official account application development (I)
What is partition and barrel division?
Why is the integer type 128 to byte -128