2014-11-21 54 views
0

我通過任何方式讀入並在同一步使小寫?

string word; 
while(cin >> myWord) 
    //put myWord in array 

讀取用戶輸入,但排序的緣故,我想「這」和「本」是相同的。對於我的排序算法,我使用默認的<和>字符串值,所以This!= this,並且爲了我的目的,我需要它==,所以我希望在讀入時立即使所有內容都小寫。從tolower我看到我需要製作一個for循環來遍歷單詞並將其設置爲小寫,所以在將單詞放入數組之前,我需要在while循環中執行此操作。但是我想知道是否有任何技巧可以讓我把這個詞放在myWord已經是小寫字母的地方(或者在閱讀完成後寫入「myWord」小寫字母)在一行中,沿着cin >> myWord.lower的方向是我在說

+0

的可能重複(http://stackoverflow.com/questions/313970/how-to-convert-stdstring-to-lower-case) – bialpio 2014-11-21 23:22:52

+0

我不確定如何在同一步驟中完成它,但可以調用[tolower](http://www.cprogramming.com/ fod/tolower.html),然後將其放入數組中以確保它是小寫字母。 – 2014-11-21 23:23:39

+0

我會改變'std :: sort'中的排序順序,通過自定義的'SortPredicate'來比較忽略大小寫的字符串。 – vsoftco 2014-11-21 23:25:49

回答

0

這就是我會爲std::string

#include <algorithm> 
#include <iostream> 
#include <locale> 
#include <string> 

struct SortNoCase // functor used to sort strings ignoring the case 
{ 
    bool operator()(const std::string& lhs, const std::string& rhs) const 
    { 
     std::string lhs_lower, rhs_lower; 
     std::transform(std::begin(lhs), std::end(lhs), 
      std::back_inserter(lhs_lower), ::tolower); 
     std::transform(std::begin(rhs), std::end(rhs), 
      std::back_inserter(rhs_lower), ::tolower); 
     return lhs_lower < rhs_lower; 
    } 
}; 


int main() 
{ 
    std::vector<std::string> vs{"Some", "strings", "THAT", "are", "UnSorted"}; 

    std::sort(std::begin(vs), std::end(vs), SortNoCase()); 

    for(auto&& elem: vs) 
     std::cout << elem << " "; 
    std::cout << std::endl; 
} 

PS做到這一點,通過使用自定義排序斷言:還有更復雜的方法,如使用自定義字符特徵,但這它和它的容易明白。如果你真的古董,可以在這裏看看:?如何的std :: string轉換爲小寫]

https://stackoverflow.com/a/5319855/3093378

0
std::for_each(myWord.begin(),myWord.end(),[] (char &c) {c=std::tolower(c);}); 
+0

如果這就是OP所需要的,那麼它完美的工作,雖然我有他的印象,他想排序的字符串數組忽略案件。 – vsoftco 2014-11-21 23:46:32

+0

@vsoftco我發現它也有點混亂。他寫道,他希望立即轉爲小寫。我希望這個班輪很快。如果他想保留案例並只改變排序順序,他肯定應該跟着你的服裝比較。 – Oncaphillis 2014-11-21 23:52:18

+0

我們只能猜測:) – vsoftco 2014-11-21 23:52:53