当前位置:网站首页>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
- Formal parameters, arguments and return values in functions
- 6-18 vulnerability exploitation - backdoor connection
- 4day
- Can I buy financial products with a revenue of more than 6% after opening an account
- 如何将一个域名解析到多个IP地址?
- QML module not found
- Selenium basic use and use selenium to capture the recruitment information of a website (continuously updating)
- Data quality: the core of data governance
- 数学规划分类 Math Programming Classfication
猜你喜欢

Jenkins+svn configuration

谷歌分析UA怎么转最新版GA4最方便

『Skywalking』. Net core fast access distributed link tracking platform

What is partition and barrel division?

kubernetes之VictoriaMetrics单节点

On the difference between break and continue statements

Xiaobai programmer's seventh day

如何将一个域名解析到多个IP地址?
![[go basics 02] the first procedure](/img/af/f32762a828f384bf6aa063ebf959aa.png)
[go basics 02] the first procedure

PySpark数据分析基础:pyspark.sql.SparkSession类方法详解及操作+代码展示
随机推荐
Whether the five distribution methods will produce internal fragments and external fragments
Some summary about function
谷歌分析UA怎么转最新版GA4最方便
[leetcode] 502.ipo (difficult)
数据质量:数据治理的核心
According to the use and configuration of data permissions in the open source framework
Div drag effect
ArcGIS中的WKID
torchvision
Selenium basic use and use selenium to capture the recruitment information of a website (continuously updating)
Playwright tutorial (I) suitable for Xiaobai
The price of dividing gold bars
Don't know mock test yet? An article to familiarize you with mock
Tfrecord write and read
Ffmpeg plays audio and video, time_ Base solves the problem of audio synchronization and SDL renders the picture
Wechat applet application development competition works comprehensive development record - Jinlu cultural tourism (cloud development - Overview)
MapGIS格式转ArcGIS方法
Virtual memory and disk
What have I experienced to become a harder tester than development?
Basic principle of torque motor control