功能 | 例子 |
---|---|
初始化 | string s; //空串 string s(“12345asdf”); |
取他的子串 | tmp = s.substr(i, wlen); //入参1,start位置; 入参2可选,长度 |
大小 | cout << s.length() << endl; cout << s.size() << endl; |
添加 | ret.push_back(tmp); |
删除 | tmp.pop_back(); |
查找 | int pos=haystack.find(needle); //类似C语言的strstr,可以直接返回具体下标 |
查看最后一个元素 | tmp.back() |
基本判断 | isalnum–数字和字母 isdigit–数字 isalpha–字母 islower–小写 isupper–大写 |
6. 函数入参
string s = "1";
Change(s);
void Change(string &s) //声明
7. 大小写和数字
transform(s.begin(),s.end(),s.begin(),::tolower);
//Applies op to each of the elements in the range [first1,last1)
//and stores the value returned by each operation in the range that begins at result.
int op_increase (int i) { return ++i; }
transform (foo.begin(), foo.end(), bar.begin(), op_increase);
8. 字符串扩充&整形转换为字符串
class Solution {
public:
static int cmp(int a, int b) {
string sa = to_string(a);
string sb = to_string(b);
return sa+sb>sb+sa;
}
string largestNumber(vector<int>& nums) {
sort(nums.begin(),nums.end(), cmp);
string s;
char tmp[10];
for (int val:nums) {
s+=to_string(val);
}
return s;
}
};
leetcode38题
class Solution {
public:
string countAndSay(int n) {
string s = "1";
while(--n) {
Change(s);
}
return s;
}
void Change(string &s) {
string tmp;
int count = 1;
for(int i = 1; i <= s.size(); i++) {
if(i != s.size() && s[i] == s[i-1]){
count++;
} else {
tmp.push_back(count+'0');
tmp.push_back(s[i-1]);
count = 1;
}
}
s = tmp;
}
};
leetcode242
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length() != t.length()) {
return false;
}
unordered_map<int, int> hash;
for (char ch: s) {
hash[ch]++;
}
for (char ch: t) {
hash[ch]--;
if(hash[ch] < 0) {
return false;
}
}
return true;
}
};