Invert a string (C language)

topic description

Invert the words in a sentence without inverting the punctuation. For example, "I like beijing.", after processing, becomes: "beijing. like I". String length does not exceed 100.

enter description

Enter a string containing only lowercase letters, spaces, '.', and the length does not exceed 100. '.' only appears at the end of the last word.

output description

Output the reversed strings in sequence, separated by spaces.

example

enter

I like beijing.

output

beijing. like I

1. Problem-solving ideas

I like beijing.

There are two ways of thinking about the inversion of this string word:

  1. First reverse the entire string
.gnijieb ekil I
  1. each word in reverse order
beijing. like I

the second

  1. First reverse each word
I ekil .gnijieb
  1. Reverse the entire string
beijing. like I

2. Realization

No matter which way of thinking to solve the problem, we need to reverse the string multiple times, so we can write a function to complete this function:

void reverse(char* left, char* right)
{
    
    
	while (left < right)
	{
    
    
		char tmp = *left;
		*left = *right;
		*right = tmp;
		left++;
		right--;
	}
}

After completing the reverse order function, you can complete the writing of the main function

int main()
{
    
    
	char arr[101] ;
	gets(arr);//gets可以读取中间有空格的字符串
	int len = strlen(arr);
	reverse(arr, arr + len - 1);//将字符串整体逆序
	char* start = arr;
	char* cur = arr;
	while (*cur)//cur指针到'\0'退出循环
	{
    
    
		//先找到一个单词的后一位
		while (*cur != ' '&&*cur!='\0')
		{
    
    
			cur++;
		}
		reverse(start, cur - 1);//将每个单词进行逆序
		start = cur + 1;//让头指针指向下一个单词的第一个
		if (*cur == ' ')//当到了整个字符串的最后一位
		//cur指向'\0'后不再后移,否则循环判断条件就会失效
		{
    
    
			cur++;
		}
	}
	printf("%s", arr);
	return 0;
}

3. Overall code and running test

#include <stdio.h>
#include <string.h>
void reverse(char* left, char* right)
{
    
    
	while (left < right)
	{
    
    
		char tmp = *left;
		*left = *right;
		*right = tmp;
		left++;
		right--;
	}
}
int main()
{
    
    
	char arr[101] ;
	gets(arr);
	int len = strlen(arr);
	reverse(arr, arr + len - 1);
	char* start = arr;
	char* cur = arr;
	while (*cur)
	{
    
    
		while (*cur != ' '&&*cur!='\0')
		{
    
    
			cur++;
		}
		reverse(start, cur - 1);
		start = cur + 1;
		if (*cur == ' ')
		{
    
    
			cur++;
		}
	}
	printf("%s", arr);
	return 0;
}

insert image description here

Tips for doing the questions
1. The scanf function will stop when it encounters a space or a newline when inputting. You can use gets to input
2. When using the pointer to move, pay attention to the position pointed by the pointer at each moment to avoid errors

Guess you like

Origin blog.csdn.net/zcxyywd/article/details/130913413