Shred string reverse [C]

Today we're going to play around with string inversion in two ways!

Topic: Invert the words in a sentence without inverting the punctuation. For example, "I like beijing." After processing, it becomes: "beijing. like I", and the length of the string does not exceed 100.

First of all, we analyze the title. Reversing the string is to exchange the position of the elements in the array to achieve the effect, but when we exchange the string before and after, ".gnijieb ekil I" will appear, which is different from our previous The goals are inconsistent, this question is special here. We need to perform a second exchange, exchange each word in the string, and treat each word as a whole and perform an array exchange.

#include<stdio.h>
#include<string.h>

int main(void)
{
	char arr[101];
	gets(arr);
	char* ph = arr;
	int sz = strlen(arr);
	exchange(arr, sz);
	while (*ph != '\0')
	{
		int count = 0;
		char* p1 = ph;
		while (*ph != ' ' && *ph != '\0')
		{
			count++;
			ph++;
		}
		exchange(p1, count);
		if (*ph != '\0')
		{
			ph++;
		}
	}
	printf("%s\n", arr);
	return 0;
}

 Why not use the scanf function? Because the scanf function will stop reading when it encounters a space in the string, at this time we can use the gets or fgets function to read the string, fgets is an upgraded version of gets, gets cannot avoid whether the number of reads exceeds the number of created string The size of the space, and fgets can be well avoided. 

Generally, fgets is used for stream input in the file, or the last item in the function parameter can be changed to stdin (keyboard stream input), and the middle parameter is the amount of data to be read.

Faced with this problem, you can also reverse the words in the string first, and then reverse the string to get similar results.

I am introducing a new method to everyone, a method with a big brain hole: we can first convert all the spaces in the array to \0, and then print the string from the back to the front. Think of each word as a small string, find the back pointer pointing to the head of the last word and print it forward, but the loop will not print the first word, so we can print the content of the pointer outside the loop to follow Topic requirements completed!

int main(void)
{
	char arr[101];
	gets(arr);
	int sz = strlen(arr);
	char* right = arr + sz -1;
	exchange(arr, sz);
	while (arr != right)
	{
		if (*right == '\0')
			printf("%s ", right+1);
		right--;
	}
	printf("%s\n", right);
	return 0;
}

These two methods reverse strings from different angles, and we can master and play with them! !

Guess you like

Origin blog.csdn.net/m0_74755811/article/details/130905314