当前位置:网站首页>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 .
边栏推荐
- 【NPP安装插件】
- C language array and bubble sort
- Tencent cloud deployment lamp_ Experience of building a station
- WPF--实现WebSocket服务端
- Multi-Modal Knowledge Graph Construction and Application: A Survey
- 基于 MinIO 对象存储保障 Rancher 数据
- Implementation of memcpy in C language
- 数字滤波器设计——Matlab
- C language functions and pointers
- Leetcode Day1 score ranking
猜你喜欢

Rand function generates pseudo-random numbers

“中国网事·感动2022”二季度网络感动人物评选结果揭晓
![[C language] string reverse order implementation (recursion and iteration)](/img/c3/02d0a72f6026df8a67669293e55ef2.png)
[C language] string reverse order implementation (recursion and iteration)
![[C language] print pattern summary](/img/48/d8ff17453e810fcd9269f56eda4d47.png)
[C language] print pattern summary

zfoo增加类似于mydog的路由
![[C language] step jumping problem [recursion]](/img/0c/32870484e89b494e41068f7c38b08e.png)
[C language] step jumping problem [recursion]

C language pointer and two-dimensional array

Item exception handling in SSM

河北:稳粮扩豆助力粮油生产提质增效

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?
随机推荐
English translation Italian - batch English translation Italian tools free of charge
河北:稳粮扩豆助力粮油生产提质增效
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?
Concurrent programming, do you really understand?
JVM (24) -- performance monitoring and tuning (5) -- Analyzing GC logs
In the second half of 2022, the system integration project management engineer certification starts on August 20
爬取IP
“中国网事·感动2022”二季度网络感动人物评选结果揭晓
基于 MinIO 对象存储保障 Rancher 数据
ssm中项目异常处理
Redis notes
[C language] Pointer elementary knowledge points
Machine learning -- model evaluation, selection and verification
The privatized instant messaging platform protects the security of enterprise mobile business
[experience] some suggestions and experience on repairing electronic equipment
Handan, Hebei: expand grassroots employment space and help college graduates obtain employment
[C language] header file of complex number four operations and complex number operations
Overcome the "fear of looking at teeth", and we use technology to change the industry
WPF -- implement websocket server
1、 Relationship among CPU, memory and hard disk