String字符串的比较和转换

来源:互联网 发布:阿里云账号能注销吗 编辑:程序博客网 时间:2024/06/03 16:13

String类里有提供了字符串的比较函数,但是它是精准比较,如果我们想做模糊比较就不好做了。msdn描述如下:

basic_string::compare

Performs a case sensitive comparison with a specified string to determine if the two strings are equal or if one is lexicographically less than the other.

平时我们很多情况都要用模糊比较,我们可以写一个函数来实现,实现如下。

bool CompareStringI(const stringstr1const stringstr2)

{

 if (str1.size() != str2.size()) {

  return false;

 }

 for (string::const_iterator c1 = str1.begin(), c2 = str2.begin(); c1 != str1.end(); ++c1, ++c2) {

  if (tolower(*c1) != tolower(*c2)) {

   return false;

  }

 }

 return true;

};

使用代码

 string s1="LOVE";

 int nResult=CompareStringI(s1,"love");

 cout<<"Result: "<<nResult<<endl;

 

大小写转换在这里就简单了

string lower = "aaaabbbbbCC";

transform(lower.begin(), lower.end(), lower.begin(), toupper);

 cout<<lower<<endl;

运行结果:

 

 

字符串转整形

 string str("1000");

 stringstream ss(str);

 double num;

 ss>>num;

 cout<<num<<endl;

 string  str1 = "125";

 wstring  str2 = L"a";

 int num_i = boost::lexical_cast<int>(str1);

//不可以转字符

// int num_i = boost::lexical_cast<int>(str2);//error

 cout<<num_i<<endl;

运行结果:

 

16进制字符转整形,这个很实用,工作中比较要转换。

const char* begin = "1b";

 char *end;

 int l = strtol(begin, &end, 16);

 cout<<l<<endl;

运行结果:

 

 

0 0
原创粉丝点击