当前位置:网站首页>Several ways of writing strings in reverse order
Several ways of writing strings in reverse order
2022-07-25 23:44:00 【Bin * Zai】
Several ways to write strings in reverse order
Tips : Reversing the order of a string is different from printing it out , Reverse order is to change the content upside down , Print in reverse order, although the print result is also reversed , However, the contents of the array storing strings have not changed .
One 、 Non recursive writing
1. Put a given string abcdef The reverse
#include <stdio.h>
int main()
{
char arr[] = "abcdef";
int sz = sizeof(arr) / sizeof(arr[0]); // Find the number of elements contained in the array ,'\0' It also includes
int left = 0;
int right = sz - 2; // reduce 2 It's because I got sz Contains '\0' This element .
while (left < right)
{
char tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
}
printf("%s", arr);
return 0;
}
The result is fedcba.
The idea in reverse order is : Swap the leftmost and rightmost characters of a string , After the exchange , Exchange the second character on the left with the second character on the right through the array subscript , By analogy , Know that the array subscript passes left++ And right–, bring left>=right.
2. Input a string by yourself , Reverse it
#include <stdio.h>
#include <string.h>
int main()
{
char arr[101] = {
0 }; // Give the character array a certain memory size , If written char arr[] = { 0 };, When inputting the array, it will cause cross-border access .
scanf("%s", arr);
int sz = strlen(arr); // The size of the given character array is 101 Under the circumstances , Only use strlen Find the length of the input string .
// use sizeof(arr)/sizeof(arr[0]) The result is the size of the array , by 101.
int left = 0;
int right = sz - 1;
while (left < right)
{
char tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
}
printf("%s", arr);
return 0;
}
Just type in a string of characters , for example :12345gf, The result is fg54321.
Be careful : For entering data into the array by yourself , Then reverse it in this case , When defining an array , Give the character array a certain memory size . If written char arr[] = { 0 };, It shows that the capacity of this array is only one byte , You can only enter one character , When inputting the array, it will cause cross-border access .
3. Encapsulate the reverse order into functions
#include <stdio.h>
#include <string.h>
void reverse(char arr[])
{
int left = 0;
int right = strlen(arr) - 1; // Encapsulated into a function, you can only use the library function to calculate the string length , Out-of-service sizeof(arr)/sizeof(arr[0])-1 This way, .
// Because the array parameter is an address .sizeof(arr) And sizeof(arr[0]) The size of is four bytes or eight bytes .
while (left < right)
{
char tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
}
}
int main()
{
char arr[] = "abcdef";
reverse(arr);
printf("%s", arr);
return 0;
}
And sizeof The difference between the two when they are used to calculate the length of a string .
Here's what's interesting , When calculating the length of a string in a user-defined function , Do not use sizeof(arr)/sizeof(arr[0])-1 This way, . Use library functions directly strlen. Because when the array passes parameters , The address of the first element of the array is passed , That is to say, although the formal parameter is written in the form of array char arr[], But the formal parameter is actually a pointer variable char*. For pointer variables , Its size depends on the compiler environment , All four bytes or all eight bytes .sizeof Operator is to get the size of data type and expression ( Company : byte ).sizeof(arr) And sizeof(arr[0]) The size of is four bytes or eight bytes . therefore sizeof(arr)/sizeof(arr[0])-1=4/4-1=0, perhaps 8/8-1=0.
Two 、 Recursive writing
1. Method 1
#include <stdio.h>
#include <string.h>
void reverse(char str[]) // Receive arguments with an array , You can also receive arguments with pointers , Such as void reverse(char* str)
{
char tmp = *str;
int len = strlen(str);
*str = *(str + len - 1);
*(str + len - 1) = '\0';
if (strlen(str + 1) >= 2) // After the end to end exchange , The remaining elements form an array , Length should be greater than 1, Talent in reverse order , There's only one element left , Indicates that it is the most intermediate element , Just put it in place .
{
reverse(str + 1);
}
*(str + len - 1) = tmp;
}
int main()
{
char arr[101] = {
0 };
scanf("%s", arr);
reverse(arr);
printf("%s\n", arr);
return 0;
}
Ideas : Suppose an array has n Elements .
In exchange for str[0] And str[n-1], Reverse the order again str[1] And str[n-2]
In exchange for str[1] And str[n-2], Reverse the order again str[2] And str[n-3]. By analogy
······
Operation steps :1. First put the first character , namely str[0] The characters in the position are placed in a temporary variable .2. Swap the last element to str[0] Where to go .3. In the string ’\0’ Put it in arr[n-1] In the right place .4. At that moment, from str[1] To str[n-2] From the perspective of , It's a new string , take str[1] And str[n-2] In exchange for .5. Assign the first character previously placed in the temporary variable to arr[n-1] In the right place .
Be careful : In the third step, the first character placed in the temporary variable is not directly transferred to str[n-1] Put on top , But through the fourth step , take str[1] And str[n-2] After exchanging , Just put the first character that has not been exchanged before str[n-1] Up . reason : If you will str[0] And str[n-1] The elements on are exchanged through a temporary variable . So for what is about to be exchanged str[1] And str[n-2] Come on , They and ’\0’ There is a gap between str[n-1] The first character on ,str[1] And str[n-2] It is impossible to exchange through the direct exchange of the first and last characters .

The reverse a b c d e f Equal to exchange a And f , Reverse the order again b c d e
The reverse b c d e Equal to exchange b And e, Reverse the order again c d. By analogy .
2. Method 2
#include <stdio.h>
#include <string.h>
void reverse(char str[], int left, int right)
{
if (left < right)
{
char tmp = str[left];
str[left] = str[right];
str[right] = tmp;
reverse(str, left + 1, right - 1);
}
}
int main()
{
char arr[101] = {
0 };
scanf("%s", arr);
int left = 0;
int right = strlen(arr) - 1;
reverse(arr, left, right);
printf("%s\n", arr);
return 0;
}
Method 2 has more parameters than method 1 , Directly exchange the first and last characters through the third temporary variable .
边栏推荐
猜你喜欢

行云管家V6.5.1/2/3系列版本发布:数据库OpenAPI能力持续强化

Leetcode 0135. distribute candy

Inheritance (the child constructor inherits the attributes in the parent constructor)

utility实用组件学习之swap,move,forward,exchange

生成随机数random学习之uniform_int_distribution,uniform_real_distribution

redis-扩展数据类型(跳跃表/BitMaps/HyperLogLog/GeoSpatial)

ABAP 代码中读取会计科目的字段状态(隐藏、可选、必输)

R language installation tutorial | graphic introduction is super detailed

Topsis与熵权法
![[Muduo] EventLoop event cycle](/img/80/824c7061d58796d454be0c438e257c.png)
[Muduo] EventLoop event cycle
随机推荐
[intelligence question] interview intelligence question
静态代理+动态代理
Graph traversal DFS, BFS (code explanation)
生成随机数random学习之uniform_int_distribution,uniform_real_distribution
Serialize operator
[QNX hypervisor 2.2 user manual]9.6 GDB
The late Apple co-founder Steve Jobs was posthumously awarded the U.S. presidential medal of freedom
ArcGIS cuts TIF images (grid data) according to the vector range, merges shp files in batches, cuts vectors in the region according to the vector range, outputs the geographic coordinate system, conve
热部署和热加载有什么区别?
Grain Academy p98 trample pit e.globalexceptionhandler: null
Regular expression (user name form verification / verification of landline number / regular replacement)
[QNX hypervisor 2.2 user manual]9.7 generate
物理防火墙是什么?有什么作用?
ratio学习之ratio_add,ratio_subtract,ratio_multiply,ratio_divide的使用
Programmer interview Golden Classic 4.12 summation path
【微信小程序】页面导航
十大排序之快速排序
行云管家V6.5.1/2/3系列版本发布:数据库OpenAPI能力持续强化
Leetcode 0135. distribute candy
Promise asynchronous callback function