2011-10-21 66 views
2

我試圖去到字符串的末尾,返回到最後一個空格,然後前進直到該單詞的結尾並將該單詞存儲在空字符串中。不允許數組或指針。C++查找返回字符串變量文本中的最後一個單詞。字符串getFirstWord(文本)

string getLastWord(string text) 
{ 
    string lastword=""; 
    int last=text.size()- 1; 
    int beginlast=0; 
    if text == ""; 
    return ""; 
    for (int i=last; i>=1; i--) 
    { 
     if (isspace(text[i])) 
      beginlast=beginlast+i; 
    } 
    for (int k=0; k!=text.size; k++) 
    { 
     if (isalpha(text[k])) 
      lastword=lastword+lastword[k]; 
    } 
    return lastword; 
} 
+0

沒有指針允許嗎?我認爲這是作業嗎? –

回答

6

你看着這個功能

string.find_last_of(' '); 

+1

我有,但我想自己寫代碼 – user1007658

+2

@ user1007658那麼,爲什麼不先從實現C++編譯器開始? std :: string是C++語言的一部分! – mloskot

0

也許是這樣的。我們先修剪掉空白。如果你想考慮其他類型,如果可忽略的空白,你可以擴大這個微不足道。

std::string input; // your data 

std::size_t pos = input.size(); 
while (input[pos] == ' ' && pos > 0) --pos; 

if (pos == 0) { /* string consists entirely of spaces */ } 

std::string result = input.substr(input.find_last_of(' ', pos)); 

做手工:

std::string input; // your data 
std::size_t pos = input.size(); 
while (input[pos] == ' ' && pos > 0) --pos; 

if (pos == 0) { /* string consists entirely of spaces */ } 

const std::size_t pos_end = pos; 
while (input[pos] == ' ' && pos > 0) --pos; 

std::string result = input.substr(pos, pos_end - pos); 
相關問題