出道题大家做做,C++的

1.      Reverse the words in a given English sentence (string) in C or C++ without requiring a separate buffer to hold the reversed string (programming)

For example:

Input:  REALLY DOGSDISLIKE MONKEYS

Output: MONKEYS DISLIKEDOGS REALLY

 

我贴上我的答案,抛砖引玉,大家帮忙看看有什么不足:

// suppose use of temp variable is allowed
// there is only one space between two words
void reverseSentence(string &strSentence)
{
    vector<string> words;
    string::size_type offsite = 0, sepIndex = string::npos; 

    // extract every words into "words"
    while ((sepIndex = strSentence.find(' ', offsite)) != string::npos)
    {
        words.push_back(strSentence.substr(offsite, sepIndex - offsite));
        offsite = sepIndex + 1;
    }
    if (strSentence.size() > offsite)
        words.push_back(strSentence.substr(offsite, strSentence.size() - offsite));
    
    if (words.empty())
        return;

    // form a new sentence
    strSentence.clear();
    size_t size = words.size();
    for (size_t u=size; u>0; u--)
    {
        if (u < size) strSentence.append(" ");
        strSentence.append(words[u - 1]);
    }
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值