Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize reverse string in C language

Shulou Source: shulou.com Published: 2022-06-02 02:40:46 10月02日 Update

This article mainly introduces how to realize the reverse string in c language, which has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let the editor take you to know it.

Reverse the string using a pointer

Train of thought:

Give two pointers, left on the left side of the string and right on the last valid character position

Swap characters in two pointer positions

Left pointer goes back, right pointer goes forward, as long as the two pointers do not meet, continue 2, after the two pointers meet, the reverse ends

Void reverse_string (char* str) {char* left = str;// first element char* right = str + strlen (str)-1

< right)//交换 { char tmp = *left; *left = *right; *right = tmp; //更新下标 left++; right--; }}int main(){ char str[] = "abcdef"; reverse_string(str); printf("%s", str); return 0;}使用递归逆序字符串 思路: 利用递归思想大事化小 先将首元素放到一个变量中 在将最后一个元素放到第一个元素位置 再将最后一个空位置放上\0便于递归逆序中间字符 最后再将首元素放到最后位置

Void reverse_string (char* str) {int len = strlen (str); char tmp = * str;// put the first element in tmp * str = * (str + len- 1); / / then put the last element in the first element position * (str + len- 1) ='\ 0' / put the last empty position on a\ 0 if (strlen (str + 1) > = 2) / / reverse reverse_string (str + 1) if the string has more than two characters; * (str + len-1) = tmp;// finally put the element just in tmp at the end of the string} int main () {char str [] = "abcdef"; reverse_string (str) Printf ("% s", str); return 0;} string with spaces in reverse order

Invert the words of a sentence without inverting punctuation. For example, I like beijing. After the function, it becomes: beijing. Like I

Enter a description:

Each test input contains 1 test case: I like beijing. Input use case length does not exceed 100

Output description:

Output the inverted string in turn, dividing it with spaces

Enter:

I like beijing.

Output:

Beijing. Like I

Train of thought:

The first step is to reverse every word

The second step is the overall reverse order

# function void reverse (char*left, char* right) {while (left) of # include / / reverse string

Tags: Character reverse string element pointer space two position word input article output idea point recursion language function vacancy test valid Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Technology Shulou Information Redmi Microsoft