C++,codewars,Stop gninnipS My sdroW!,5264d2b162488dc400000001

/*
codewars,Stop gninnipS My sdroW!,5264d2b162488dc400000001
设计一个函数,获取一个字符串, 将该字符串中长度大于等于5的单词反转,
将反转后的内容作为新字符串返回
*/
#include <string>
#include <iostream>
#include <algorithm>
std::string spinWords(const std::string &str)
{
    std::string ans="";
    std::string word="";//储存连续的非空格字符
    for(char ch : str){
        if(ch==' '){
            //ans,先接上word,再接上空格
            if(word.size()>=5){
                std::reverse(word.begin(),word.end());
            }
            ans+=word;
            word="";
            ans+=' ';
        }else{
            word+=ch;
        }
    }
    if(word.size()>=5){
        std::reverse(word.begin(),word.end());
    }
    ans+=word;
    return ans;
}
int main(){
    std::string str="Hey fellow warriors";
    std::cout<<spinWords(str)<<std::endl;
    return 0;
}
posted @ 2025-03-07 20:14  Kazuma_124  阅读(16)  评论(0)    收藏  举报