C++不区分大小写比较string类似CString.compareNoCase
生活随笔
收集整理的這篇文章主要介紹了
C++不区分大小写比较string类似CString.compareNoCase
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用transform();全轉化為小寫,然后對比string
#include?<string>#include?<algorithm>
using?namespace?std;
namespace?BaseFunc
{
????//?string轉小寫
????string?strToLower(const?string?&str)
????{
????????string?strTmp?=?str;
????????transform(strTmp.begin(),strTmp.end(),strTmp.begin(),tolower);
????????return?strTmp;
????}
????//?string.compareNoCase
????bool?compareNoCase(const?string?&strA,const?string?&strB)
????{
????????string?str1?=?strToLower(strA);
????????string?str2?=?strToLower(strB);
????????return?(str1?==?str2);
????}
????//?另一法
????bool?compare(const?string&?x,?const?string&?y)
????{
????????string::const_iterator?p?=?x.begin();
????????string::const_iterator?q?=?y.begin();
????????//?遍歷對比每個字符
????????while?(p?!=?x.end()?&&?q?!=?y.end()?&&?toupper(*p)?==?toupper(*q))
????????{
????????????++p;
????????????++q;
????????}
????????if?(p?==?x.end())?//?如果x到結尾,y也到結尾則相等
????????{
????????????return?(q?==?y.end());
????????}
????????if?(q?==?y.end())?//?如果x未到結尾,y到結尾返回false
????????{
????????????return?false;
????????}
????????//?如果x,y都沒有到結尾,說明有不相同的字符,返回false
????????return?false;
????????//return?(toupper(*p)?<?toupper(*q));
????}
}
void?main()
{
????string?strA?=?"abc";
????string?strB?=?"AdC";
????bool?b?=?BaseFunc::compareNoCase(?strA,?strB?);
????b?=?BaseFunc::compare(?strA,?strB?);
}
string與CString互相轉換:
string str;CString s;s = str.c_str();str = s;url:http://greatverve.cnblogs.com/archive/2012/12/08/string-compareNoCase.html?
轉載于:https://www.cnblogs.com/greatverve/archive/2012/12/08/string-compareNoCase.html
總結
以上是生活随笔為你收集整理的C++不区分大小写比较string类似CString.compareNoCase的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用reserve函数避免vector和
- 下一篇: s3c2440移植MQTT