String

String Definition

String Basic Operation

string STL()

Append()

std::string s="C+";
string ch="+";

//append string
s.append(ch);
//append char, append(number of characters to copy, character value)
char sh='+';
s.append(1,sh);

//append partial string, append(string, [optional]subpos, sublen)
string str="writing";
s.append(str,6,3);

append char to end of string

std::string s="C+";
char ch='+';

//push_back()
s.push_back(ch);
//+=operator
s+=ch;
//append()
s.append(1,ch);

string&char&int conversion

//using stringstream class

//using std::stoi()
string str="45";
int num = std::stoi(str);

//int to string


//char shift
char a = 'a';
char b = a+1;
  • 249 Group Shifted Strings(Q:A)

char&int conversion

Non-ASCII Delimiter

char x=(char)257;
  • 271 Encode and Decode Strings(Q:A)

Chunked Transfer Encoding

chunked

  • 271 Encode and Decode Strings(Q:A)

Topic

Substring

  • 187 Repeated DNA Sequences(Q:A)(Hash Table)

Palindrome, Permutation, Combination

  • 131 Palindrome Partitioning(Q:A)
  • 267 Palindrome Permutation(Q:A)
  • 247 Strobogrammatic Number II(Q:A)(DP,Backtracking)

String Conversion

  • 91 Decode Ways(Q:A)(double DP)
  • 320 Generalized Abbreviation(Q:A)(backtracking)

String Distance

  • 244 Shortest Word Distance II(Q:A)(Hash Table and two pointers)

  • 245 Shortest Word Distance III(Q:A)

Using string for math calculation

  • 227 Basic Calculator II(Q:A)(stack)

keep in mind data structure: stack::top() -> sign -> tmp -> s[i]

Advanced Topics

Greedy

  • 316 Remove Duplicate Letters(Q:A)

How to remove certain characters that occured in a string:

s.erase(std::remove(s.begin(), s.end(), c), s.end());
  • std::remove std::remove moves the non-removed items to the front of the vector and returns an iterator pointing just beyond the last unremoved item.

For instance, "cbacdcbc" as input:

auto it=std::remove(s.begin(),s.end(),'b');
cout<<it-s.begin()<<endl;
cout<<s<<endl;

Output:

6
cacdccbc
cacdcc
  • std::erase
    1. string::erase() erases all characters in a string
    2. string:erase(size_type pos) erases all characters after position pos
    3. string::erase(size_t idx, size_t len) erases len length characters starting at index idx.
    4. string::erase(iterator pos) erase the single character at iterator position pos.
    5. string::erase(iterator begin, iterator end) erase characters from iterator pos to another iterator pos.
PREVIOUSHash Table
NEXTHeap