程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 出道題大家做做,C++的(含答案)

出道題大家做做,C++的(含答案)

編輯: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

 

我貼上我的答案,拋磚引玉,大家幫忙看看有什麼不足:

[cpp] 
// 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]); 
    } 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved