收集一些字符串的用法
反转字符串
// 反转 std::string s="HelloWorld"; std::string sr; std::reverse(s.begin(), s.end()); // 反转字符串到另外一字符 sr.assign(s.rbegin(), s.rend());
判断字符串是字符是某个字符串开始或者结尾
std::string s("hello, world"); std::string head("hello"); std::string tail("ld"); bool startwith = s.compare(0, head.size(), head) == 0; bool endwith = s.compare(s.size() - tail.size(), tail.size(), tail) == 0;
转换类型(toint, todouble)
std::string s("123"); int i = atoi(s.c_str()); std::string sd("12.3"); double d = atof(sd.c_str());
替换字符串
std::string str("hello, world"); std::string sub("ello, "); str.replace(str.find(sub), sub.size(), "appy ");
删除字符
std::string str = " heLLo "; str.erase(0, str.find_first_not_of(" ")); str.erase(str.find_last_not_of(" ")+1);
删除特定字符
std::string str = " hello, world. say bye "; str.erase(remove_if(str.begin(),str.end(), bind2nd(equal_to(), ' ')), str.end());
大小写
std::string str = "heLLo"; std::transform(str.begin(), str.end(), str.begin(), toupper); std::transform(str.begin(), str.end(), str.begin(), tolower);