This code implements a string reverse order function Reverse
, and accepts the string input by the user in the main
function, and then calls a> Reverse
The function performs reverse order operation and finally outputs the reversed string.
//逆序字符串(递归)
void Resever(char *str) //str这个指针指向数组首元素的位置
{
char temp = *str; //将str指向的元素赋给临时变量temp
int len = strlen(str); //求字符串长度
*str = *(str + len - 1); //将剩余字符串最后一个元素赋值给str指向的位置
*(str + len - 1) = '\0'; //将剩余字符最后一个元素设置为\0
if (strlen(str+1)>=2) //判断剩余字符数是否大于等于2,若是,则继续递归
{
Resever(str + 1);
}
*(str + len - 1) = temp; //将temp存起来的值赋给字符串末尾
}
int main()
{
char arr[20] = "";
printf("请输入一个字符串");
scanf("%s", arr);
Resever(arr);
printf("逆序之后为: %s", arr);
return 0;
}
The specific explanation is as follows:
-
void Reverse(char *str)
Function:
char *str
is a pointer to the first element of the character array, used to receive the string to be reversed.
char temp = *str;
Save the first character pointed to by the pointer str
into the temporary variable temp
.
int len = strlen(str);
Use the strlen
function to get the length of the string.
*str = *(str + len - 1);
Replaces the first character of the string with the last character of the string.
*(str + len - 1) = '\0';
Set the last character of the original string as the string terminator \0
, which can truncate the original string.
if (strlen(str + 1) >= 2)
Determine whether the remaining number of characters is greater than or equal to 2. If so, call the Reverse
function recursively to perform reverse order operations on the remaining strings.
*(str + len - 1) = temp;
Place the previously saved first character temp
back to the end of the string.
-
int main()
Function:
- Create a character array
arr
to store the string entered by the user.
- Use
scanf("%s", arr);
to accept a string entered by the user.
- Call
Reverse(arr);
to perform reverse order operation on the input string.
- Use
printf("逆序之后为: %s", arr);
to output the string in reverse order.
Required knowledge points:
- Representation and operation of strings: Strings in C language are stored in the form of character arrays, ending with \0. Strings can be easily manipulated using character pointers.
- Pointers and pointer operations: The code uses pointers to operate array elements. For example,
*str
means getting the value pointed by the pointer, str + len - 1
means moving the pointer to the array. somewhere in.
- Recursion: The function uses recursive calling itself to implement the reverse order operation of the string.
- String input and output: Use
scanf
to input a string, and use printf
to output a string.