C/C++ Programming Learning-Week 7⑦ Word Flip

Topic link

Title description

Enter a sentence (one line), flip each word in the sentence and output it.

The input format is
only one line, a character string, and no more than 500 characters. Separate words with spaces.

Output format
Reverse the string after each word, and the spaces between words must be consistent with the original text.

Note
that there may be spaces at the beginning and end of the string.

Sample Input

hello world

Sample Output

olleh dlrow

Ideas

Input a line of string with spaces, and output each word in reverse order. The reverse output is output from back to front.

C language code:

#include <string.h>
#include <stdio.h>
char s[10005];
int main()
{
    
    
    int len, position, sum = 0, i, j;
    gets(s);		//输入
    len = strlen(s);//求字符串长度
    s[len] = ' ';	//末尾加一空格方便计算
    for(i = 0; i <= len; i++)
    {
    
    
        if(s[i] != ' ') sum++;	//计算单词长度
        else
        {
    
    
            position = i;		//记录单词末位置
            for(j = 1; j <= sum; j++)	//倒序输出
                printf("%c", s[--position]);
            sum = 0;//计数器归零
            if(i != len) printf(" ");
        }
    }
    printf("\n");
    return 0;
}

C++ code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	char a[510];
	cin.getline(a, 510);
	strcat(a, " ");
	int len = strlen(a), pos1 = 0, pos2;
	for(int i = 0; i < len; i++)
		if(a[i] == ' ')
		{
    
    
			pos2 = i;
			for(int j = pos2 - 1; j >= pos1; j--)
				cout << a[j];
			cout << " ";
			pos1 = pos2 + 1;
		}
	return 0;
}

For students who don’t have C language foundation, you can learn the C language grammar first. I will sort it out and send it out later.
I have already written it. You can go to the C language programming column to see the content of the first week .

Other exercises this week:

C language programming column

C/C++ Programming Learning-Week 7① Calculate the value of (a+b)*c

C/C++ Programming Learning-Week 7② Calculate the value of (a+b)/c

C/C++ Programming Learning-Week 7 ③ Kakutani Conjecture

C/C++ programming learning-week 7④ cocktail therapy

C/C++ Programming Learning-Week 7 ⑤ The number of the same number as the specified number

C/C++ Programming Learning-Week 7 ⑥ Group photo effect

C/C++ Programming Learning-Week 7⑦ Word Flip

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/112912192