当前位置:网站首页>Reverse string
Reverse string
2022-07-28 20:10:00 【Boring ~】
Two ideas of reverse string ( Before you get the idea , First analyze , Only analysis can lead to ideas ):
analysis : The problem of reverse string is solved by drawing
What was stored in the original array was “abcde", Now let's save the title ”edcba", That is to say a The position of is now put e This value ,e The position of is now put a Value , And so on , That is, the two values are exchanged , That is to exchange things between the two rooms . So at this time, the idea came out , Find the value in the element by accessing the subscript or address , Then exchange , There are several groups that need to be exchanged , So we need to use circular statements to realize .
After the first idea comes out , If you think about recursive algorithm, it will be much simpler .
Before using recursive algorithm , First create a function , The function of the function is to reverse the string abcde, By thinking about the first way , You can reverse the order abcdef Turn into : Exchange first a and e, Add the reverse order bcd, The reverse bcd Can be converted to : Exchange first b and d, At this time, it is found that the string passed in has only one character , There is no need to exchange .
The first way of thinking : First step : Find two characters before and after , The second step : swapping
The second way of thinking : Use recursive algorithms , First step : Find the leftmost and rightmost elements , The second step : swapping , The third step : Give the rest of the string to your own function .
There are two ways to find characters , One is because the string is put into the array , Locate elements by accessing subscripts , Another way is to locate elements by address .
The first one is :
Locate elements by accessing subscripts
#include<stdio.h>
#include<string.h>
// Find the element by subscript
// Implementation function
void reverse(char* arr)
{
// Find the subscript for the element
int left = 0;
int right = strlen(arr) - 1;
// Exchange values
int i = 0;
int avg = (left + right) / 2;
for (i = 0;i < avg;i++)
{
int tmp = 0;
tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
}
}
int main()
{
char arr[] = "abcdefg";
// Create a function to realize the inverse function
reverse(arr);
// Print array
printf("%s", arr);
return 0;
}
Locate elements by address
#include<stdio.h>
#include<string.h>
// Find the element by address
// Implementation function
void reverse(char* arr,int str )
{
// Through the address , Element found
char* left = arr;
char* right = arr + str - 1;
// In exchange for
int avg = str / 2;
int i = 0;
for (i = 0;i < avg;i++)
{
char tmp = 0;
tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
int main()
{
char arr[] = "abcdefg";
int str = strlen(arr);
// Create a function , Realize the reverse function
reverse(arr,str);
// Print array
printf("%s", arr);
return 0;
}
The second kind :
Locate elements by accessing subscripts
#include<stdio.h>
#include<string.h>
// Implementation function
void reverse(char* arr)
{
// Find the left and right characters , Complete the exchange
// Because every time the string passed in is a new string , So every time we have to redefine the subscript
int left = 0;
int right = strlen(arr)-1;
char tmp = 0;
tmp = arr[left];
arr[left] = arr[right];
arr[right] = '\0';
// Call your own function , Complete the exchange of the remaining characters
if (*(arr + 1) != '\0')
{
reverse(arr + 1);
}
arr[right] = tmp;
}
int main()
{
char arr[] = "abcdefg";
// Create a function
reverse(arr);
// Print function
printf("%s", arr);
return 0;
}
Find the element by address
#include<stdio.h>
#include<string.h>
// Implementation function
void reverse(char* arr)
{
// Find the left and right subscripts through the address , And exchange
char tmp = *arr;
int len = strlen(arr);
*arr = *(arr + len - 1);
*(arr + len - 1) = '\0';
// Call its own function , Complete the inversion of the intermediate string
if (*(arr + 1) != '\0')
{
reverse(arr + 1);
}
*(arr+len-1) = tmp;
}
int main()
{
char arr[] = "abcdefg";
// Create a function
reverse(arr);
// Print the inverted array on the console
printf("%s", arr);
return 0;
}
When using recursive algorithm matters needing attention :
One : When the leftmost and rightmost characters are found by subscript , Every time you call your own function , The string passed to the function changes every time , Length will change , So the rightmost subscript will change , Think about it , The leftmost subscripts start with 0, Don't touch it .
Two : Through the address , Find the characters , In exchange , To really operate on the elements in the array , Instead of copying values , Copy to a variable , Operate on variables , Don't get the object of operation wrong . Copy words , Only for the value of the copy , That is to say, we have operated the separation , And the real body doesn't move .
The following is the wrong approach to the second note :
#include<stdio.h>
#include<string.h>
// Implementation function
void reverse(char* arr)
{
// Find the left and right subscripts through the address , And exchange
char left = *arr;
int len = strlen(arr);
char right = *(arr + len - 1);
char tmp = left;
left = right;
right = '\0';
// Call its own function , Complete the inversion of the intermediate string
if (*(arr + 1) != '\0')
{
reverse(arr + 1);
}
right = tmp;
}
int main()
{
char arr[] = "abcdefg";
// Create a function
reverse(arr);
// Print the inverted array on the console
printf("%s", arr);
return 0;
}
You can see , Array is not inverted .
In the code , Created left and right Variable , Copy the value into these two variables , Just operate on variables , That is, only the copied values are operated , There is no real operation on the real body .
边栏推荐
- Rand function generates pseudo-random numbers
- [C language] Fibonacci sequence [recursion and iteration]
- Leetcode Day1 score ranking
- [C language] step jumping problem [recursion]
- 9. Pointer of C language (3) classic program, exchange the value of two numbers for deep analysis, (easy to understand), are formal parameters and arguments a variable?
- 9. Pointer of C language (4) pointer and one-dimensional array, pointer operation
- 【NPP安装插件】
- Information management system and games based on C language
- [C language] advanced pointer exercise 1
- Common APIs in string
猜你喜欢
2. Floating point number, the difference between float and double in C language and how to choose them
[C language] print pattern summary
Item exception handling in SSM
CDGA|工业互联网行业怎么做好数据治理?
Theoretical knowledge of digital image (I) (personal analysis)
Know small and medium LAN WLAN
[C language] string reverse order implementation (recursion and iteration)
河北:稳粮扩豆助力粮油生产提质增效
Store and guarantee rancher data based on Minio objects
5. Difference between break and continue (easy to understand version)
随机推荐
8. Compilation errors of C language and Chinese explanation
Return and job management of saltstack
English Translation Spanish - batch English Translation Spanish tools free of charge
[C language] initial C language reflection and summary
KPMG China: insights into information technology audit projects of securities fund management institutions
Can China make a breakthrough in the future development of the meta universe and occupy the highland?
Cdga | how can the industrial Internet industry do a good job in data governance?
[C language] Pointer elementary knowledge points
How to write the SQL statement of time to date?
Rand function generates pseudo-random numbers
1. C language variable type, global variable, local variable
Handan, Hebei: expand grassroots employment space and help college graduates obtain employment
云原生编程挑战赛火热开赛,51 万奖金等你来挑战!
跨区域网络的通信学习静态路由
There is a 'single quotation mark' problem in the string when Oracle inserts data
BeanFactory not initialized or already closed - call ‘refresh‘ before accessing beans via the Applic
Tencent cloud deployment lamp_ Experience of building a station
MySQL command statement (personal summary)
C language functions and pointers
7. Functions of C language, function definitions and the order of function calls, how to declare functions, prime examples, formal parameters and arguments, and how to write a function well