The substr() Function

◀ The append() Function▶ The insert() Function
Amazon You can use this function to return a substring of the invoking string object. This function is very useful in manipulating a string because extracting a part of a string is very common in programming. Here’s its prototype:
string substr(int pos = 0, int n = string::npos) const;
It returns a string copied starting at index pos for n characters or up to the end of the invoking string object, whichever comes first.

If only pos is supplied, the function returns the string copied starting at index pos until the end of the invoking string object. If no arguments are supplied, the function simply returns a string identical to the invoking string object. Here are a couple of examples:

string s = "thanks for help, Kathy";
cout << s.substr(7, 3) << endl; /* print "for" */
cout << s.substr(17) << endl; /* print "Kathy" */

Extracting a portion of a string is an extremely common task; so make sure you know how to do it! Next let’s look at how to insert a string in the middle of another string!
◀ The append() Function▶ The insert() Function

fShare
Questions? Let me know!