当前位置:网站首页>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;
}

边栏推荐
- Title: give a group of arrays, arranged from large to small and from small to large.
- After 2 years of functional testing, I feel like I can't do anything. Where should I go in 2022?
- 4day
- Having met a tester with three years' experience in Tencent, I saw the real test ceiling
- What should I do if I encounter the problem of verification code during automatic testing?
- QML module not found
- Xiaobai programmer's fourth day
- JS interview questions
- TFrecord写入与读取
- Xiaobai programmer's first day
猜你喜欢

Playwright tutorial (II) suitable for Xiaobai

How to implement an app application to limit users' time use?

Redis基础2(笔记)

Smart S7-200 PLC channel free mapping function block (do_map)

MySQL - subquery - column subquery (multi row subquery)

QML module not found

【C语法】void*浅说
![[C syntax] void*](/img/34/b29b7bbf8eae9f1730352cac1301a4.png)
[C syntax] void*

ML-Numpy

Data quality: the core of data governance
随机推荐
vim用法记录
Wkid in ArcGIS
Application of breakthrough thinking in testing work
torchvision
ThreadLocal 总结(未完待续)
D3.js 学习
Three ways to allocate disk space
Can I buy financial products with a revenue of more than 6% after opening an account
[C syntax] void*
Leetcode 106. construct binary tree from middle order and post order traversal sequence
scrapy无缝对接布隆过滤器
ArcGIS10.2配置PostgreSQL9.2标准教程
Call of addition, subtraction, multiplication and division of integer type only
The testing work is not valued. Have you changed your position?
MySQL - subquery - column subquery (multi row subquery)
Flex layout
完啦,上班三个月,变秃了
Build commercial projects based on ruoyi framework
核电站在席卷欧洲的热浪中努力保持安全工作
Smart S7-200 PLC channel free mapping function block (do_map)