#C++#

Operation on string

##length of string## s.size()

##append## string str; string str2=”Writing “; string str3=”print 10 and then 5 more”;

str.append(str2);
//"Writing "
str.append(str3, 6, 3);//6 is subpos, 3 is sublen
//start from index 6 and length=3
//"10 "
str.append("dots are cool", 5)
//"dots are cool"pointer to an array of characters
// 5 is the number of characters to copy
//"dots "
str.append("here: ")
//"here: "
str.append(10u, '.');
//10u number of characters
//'.' character value, repeated n times
//".........."
str.append(str3.begin()+8, str3.end());
//str3.begin()+8 inputIterator first
//str3.end() inputIterator last
//" and then 5 more"
str.append<int>(5, Ox2E)
//ascii hex 2E
//"....."
std::cout<<str<<"\n";
//prints"Writing 10 dots here: .......... and then 5 more....."

##push_back## //appends character c to the end of the string //increase its length by 1 push_back(c);

##pop_back## //delete last character string str (“hello world!”); str.pop_back(); cout«str«“\n”; \prints “hello world”

##insert## insert(size_t pos, const string& str)?

##substr## string substr(size_t pos, size_t len) const; string str=”We think in generalities” string str2=str.substr(3,5) //str2 = “think”

##compare## int compare (const string& str) //return 0 if equal //return <0 if lower or shorter //return >0 if greater or longer string str1(“green apple”); string str2(“red apple”);

int i=str1.compare(str2);
//return <0

##reverse a string## string reversed(temp.rbegin(), temp.rend()); string::rbegin() and string::rend(), which stand for “reverse begin” and “reverse end” respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator* to dereference to an element, i.e. a character of the string, and operator++ to advance to the “next” element), such that rbegin() points to the last character of the string, rend() points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).

Finally, the constructor we are passing these iterators into is a string constructor of the form:

template <typename Iterator>
string(Iterator first, Iterator last);

which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.

##Problem Set##

Interconvert Integer and String

string IntToString(int x){
	bool isNegate=false;

	if(x<0){
		isNegate=true;
		x=-x;
	}
	
	string s="";
	while(x!=0){
		s+='0'+abs(x%10);
		x=x/10;
	}

	if(isNegate){
		s+='-';
	}
	return {s.rbegin(), s.rend()};
}

int StringToInt (const string& s){
	int x=0;
	for(i=s[0]=='-'?1:0, i<s.size(); i++){
		x+=x*10+(s[i]-'0');
	}
	return s[0]=='-'?-x:x;
}

Longest Palindrome Implement strStr() Valid Palindrome Longest Palindromic Substring