字符串去除前后空格
void trim(string &s){
if(!s.empty() ){
s.erase(0, s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
}
}
对map和set进行排序
可以将元素项转换为vector的元素,然后排序后输出
using namespace std;
bool cmp(pair<string, int> &left, pair<string, int> &right){
return left.second < right.second;
}
int main(){
map<string, int> ma;
ma["Alice"] = 86;
ma["Bob"] = 78;
ma["Zip"] = 92;
ma["Stdevn"] = 88;
vector<pair<string, int> > vec(ma.begin(),ma.end());
sort(vec.begin(),vec.end(),cmp);
for (vector<pair<string, int> >::iterator it = vec.begin(); it != vec.end(); ++it){
cout << it->first << " " << it->second << endl;
}
return 0;
}
按某字符分割字符串
using namespace std;
vector<string> split(string src, char c) {
stringstream temp(src);
string s;
vector<string> v;
while (getline(temp, s, c)) {
v.push_back(s);
}
return v;
}
字符串数字互转
using namespace std;
// 数字转字符串
void toString(string &s, int &num){
stringstream ss;
ss << num;
ss >> s;
}
// 字符串转数字
void toInt(string &s, int &num){
stringstream ss;
ss << s;
ss >> num;
}
int main(){
string s;
int num = 10;
toString(s, num);
cout << s << endl;
s = "999";
toInt(s, num)
cout << num << endl;
return 0;
}