1) 在中,size()与length()的实现是一样的,都返回string的长度

图片.png

2) 截取部分字符串

string.substr(beginPose,endPose)

  1. string line = "(a,b,c,d)";
  2. line = line.substr(1,line.size()-2);
  3. // line == "a,b,c,d"

1) geiline:https://www.cnblogs.com/xiaofeiIDO/p/8574042.html

  1. #include<iostream>
  2. #include<string>
  3. string text;
  4. std::getline(std::cin,text);
  5. ifstream inFile;
  6. inFile.open("Hello.txt", ios::in);
  7. if(!inFile.is_open())
  8. return false;
  9. while(std::getline(inFile,text)){
  10. /* code */
  11. }

简单算法的实现

1) KMP

  1. int* getNext(string p)
  2. {
  3. int* next = new int[p.length()];
  4. next[0] = -1; //while the first char not match, i++,j++
  5. int j = 0;
  6. int k = -1;
  7. while (j < (int)p.length() - 1)
  8. {
  9. if (k == -1 || p[j] == p[k])
  10. {
  11. j++;
  12. k++;
  13. next[j] = k;
  14. }else{
  15. k = next[k];
  16. }
  17. }
  18. return next;
  19. }
  20. int KMP(string ts,string ps)
  21. {
  22. int i=0;
  23. int j=0;
  24. int* next=getNext(ps);
  25. while (i < (int)ts.length() && j < (int)ps.length())
  26. {
  27. if (j == -1 || ts[i] == ps[j])
  28. {
  29. i++;
  30. j++;
  31. }else{
  32. j=next[j];
  33. }
  34. }
  35. if (j == (int)ps.length()){
  36. return i-j;
  37. }
  38. return -1;
  39. }

2) 字符串分割

substr(起始位置,需要分割的长度);

  1. /*字符串分割算法*/
  2. vector<string> splitOnce(const string& line, const string& op){
  3. vector<string> result;
  4. /*使用KMP算法匹配字符串*/
  5. int pose = KMP(line,op);
  6. result.push_back(line.substr(0,pose));
  7. result.push_back(line.substr(pose+op.size(),line.size()));
  8. return result;
  9. }
  10. vector<string> split(const string& line, const string& op){
  11. vector<string> result;
  12. int pose;
  13. string text(line);
  14. while (true)
  15. {
  16. pose = KMP(text,op);
  17. if(pose == -1)
  18. break;
  19. result.push_back(text.substr(0,pose));
  20. text = text.substr(pose+op.size(),text.size());
  21. }
  22. result.push_back(text);
  23. return result;
  24. }

3) 大小写转换

  1. 统一转成大写:ch & 0b11011111 简写:ch & 0xDF
  2. 统一转成小写:ch | 0b00100000 简写:ch | 0x20
    1. if((s.charAt(i ++) & 0xDF) != (s.charAt(j --) & 0xDF)) return false;

STL/alog 函数

1. 反转字符串

  1. string a = "hello";
  2. reverse(a.begin(),a.end()); // olleh