String (C++ class)¶
Basics¶
string header
#include <string>Constructors
Common methods
at()returns a reference variable so you can assign value to it!size()/length()operator+()allowsstr1 + str2clear()clears the content of a stringempty()check empty
I/O
read from cin
>>extractiongetline
1// when a getline is used after >> 2// to avoid reading in an empty string 3 4int val1; 5string restOfTheLine; 6 7// method 1, recommended in projects 8cin >> val1; 9do { 10 getline(cin, restOfTheLine); 11} while (restOfTheLine.empty()); 12 13// method 2, cin.ignore() 14cin >> val1; 15// cin.ignore(); // usually enough, clear up to 1 character till the new line 16cin.ignore(numeric_limits<streamsize>::max(), '\n'); // clear all till the new line 17getline(cin, restOfTheLine); 18 19// method 3, the std::ws manipulate 20cin >> val1; 21getline(cin >> ws, restOfTheLine); 22 23// method 3a 24cin >> val1 >> ws; 25getline(cin, restOfTheLine);
write to terminal
<<insertion
string algorithms
most are similar to 1d array
Advanced¶
More methods
string::find()find the first occurrence of a character or a sub-stringstring::substr()extract a sub-stringstring::push_back()add a character at the endstring::insert()insert a string to a positionstring::replace()replace a sub-string with a stringstd::to_string()convert a numeric value to a stringstd::stoi(),std::stod()convert a string to an int or double value
Extract data from a string (parsing)
alternative method: istringstream
Generate (formatted) text based on data
alternative method: ostringstream
1// Patient data with name, age and gender formatted as a string like
2// John Smith, 21, Male
3
4class Patient {
5 string name;
6 age int;
7 string gender;
8 public:
9 void parse(const string &text);
10 string toStr();
11}
12
13void Patient::parse(const string &text) {
14 int firstComma = text.find(',');
15 int secondComma = text.find(',', firstComma + 1);
16 name = text.substr(0, firstComma);
17 age = stoi(text.substr(firstComma + 2, secondComma - firstComma - 2));
18 gender = text.substr(secondComma + 2, text.length() - secondComma -2);
19}
20
21void Patient::toStr() {
22 return "Name: " + name + " | Age: " + to_string(age) + " | Gender: " + gender";
23}