Sie sind auf Seite 1von 2

/*

* File: 20160927_CPP_L12.cpp.
* Title: 2016-09-27 C++ Lesson 12
* Author: Renato Montes
* Description: Notes for Albert Wei's C++ class
*/

//MORE COMMENTS ON STRING.PDF

string uppercase(const string& s){


for (char c : s) //range-based for-loop
c = toupper(c);
return s;
}

//in main:
cout << uppercase(s) << endl;

string uppercase2(const string& s){


for (char& c : s) //need the & to change to uppercase!!!!
c = toupper(c);
return s;
}

string uppercase3(const string& s){


for (auto& c : s) //the compiler deduces, with auto-deduction, that c
// is a constant char, so it becomes const char&
// and you can't assign to a const char in next line
c = toupper(c);
return s;
}

//append is similar to +=
s1 =+ s2;
s1.append(s2);

//insert is always insert before

/* Search functions */

//rfind is reverse find

//find first of looks for the first occurrence of a character in the passed
// string: find_first_of("abc") looks for first occurrence of a, b or c

//find can have a second argument to be told where to start looking


s.find("abc", 5) //we start looking at position index 5

//if nothing is found, find() returns string::npos

//need to create
string::size_type idx;
//to store the index
//then if statement with equals to string::npos as in the sheet
//The program "replace"
//commmandline:
./replace hello world! < ___ > ___

/** study the program */


//notice how idx += nslen; does NOT use oslen instead
//testing is important, there are special cases

//Example
"ab:c;d.ef:gh;.ij" //delimiters: ":;."
//tokenize (i.e. break up) the string at the delimiters
"ab" "c" "d" "ef" "gh" "ij" //no empty tokens

string next_token(const string& s, const string& delim,


string::size_type& start) {
//passing start by reference!
string::size_type pos = s.find_first_not_of("delim, start);
//the first non-delimiter is the beginning of the tokens
if (pos == string::npos) //no more non-delimiter; hence no more tokens
// return "";
start = s.find_first_of(delim, pos); //the next delimiter terminates the
// token
return (start == string::npos) ? s.substr(pos) : s.substr(pos, start - pos);
}
//the return above is the technically correct version
//there's a simpler version of the return:
return s.substr(pos, start-pos);
//why? this will work even when start is string::npos
//take the rest of the string

vector //like a dynamic array that can grow at the end


// cannot grow at the beginning

vector<int> v; //empty vector


v.push_back(3);
v.push_back(2);

//Program that returns a vector of


vector<string> tokenize(const string& s, const string& delim) {
string::size_type i = 0;
string token;
vector<string> v;
while ((token = next_token(s, delim, i)) != "")
v.push_back(token);
return v;
}
//thus we get a container with all the tokens

Das könnte Ihnen auch gefallen