当前位置:网站首页>Hj31 word inversion

Hj31 word inversion

2022-04-23 15:12:00 coder_ Alger

describe

Invert all the words in the string .

explain :

1、 The characters that make up a word are 26 A capital or lowercase letter ;

2、 Characters that do not make up a word are treated as word separators ;

3、 The inverted word spacer is required to be represented by a space ; If there are multiple separators between adjacent words in the original string , Only one space spacer is allowed after inverted conversion ;

4、 Each word is the longest 20 Letters ;

Example 1

Input :

I am a student

Copy output :

student a am I

Copy

Example 2

Input :

$bo*y gi!r#l

Copy output :

l r gi y bo
#include <iostream>
using namespace std;
#include <string>
#include <vector>

int Word_Rev(string str)
{
    vector<string>vec;// Use vectors to store words 
    int len = str.size();
    int sublen = 0;// Record the length of each substring 
    
    // Split the words in the sentence 
    for(int i = 0;i<len;i++)
    {
        if((str[i]>='a'&&str[i]<='z') || (str[i]>='A'&&str[i]<='Z'))
        {
            sublen++;
            continue;
        }
        else
        {
            // Be careful : If there is no special character after the last word , I can't get there 
            if(sublen>0)
            {
                vec.push_back(str.substr(i-sublen,sublen));
                sublen = 0;
            }
        }
    }
    
    // Write the last word to the vector 
    if(sublen>0)
    {
        vec.push_back(str.substr(len-sublen,sublen));
    }
    
    // Output in reverse order 
    for(vector<string>::reverse_iterator it = vec.rbegin();it != vec.rend();it++)
    {
        cout<<*it<<" ";
    }
    cout<<endl;
    return 0;
}


int main()
{
    string str;
    while(getline(cin,str))
    {
        Word_Rev(str);       
    }
    return 0;
}

版权声明
本文为[coder_ Alger]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231507258849.html