150 likes | 222 Views
Strings in C++. To use "new" strings in C++. to use string CONSTANTS in double quotes, just use them - no library needed to use string variables and functions , you must #include <string> declare string variables assignment statement input with extraction operator
E N D
To use "new" strings in C++ • to use string CONSTANTS in double quotes, just use them - no library needed • to use string variables and functions, you must #include <string> • declare string variables • assignment statement • input with extraction operator • output with insertion operator
String Operators and Methods • concatenation • dot notation • length() • substr() • find()
concatenation • operator is + • at least one of the two operands must be a string variable • example call: if name = “Bob”, expression name + "by Roberts" results in one string "Bobby Roberts" • does not automatically put spaces in
length method • Function length returns an unsigned integer value that equals the number of characters currently in the string • Functionsizereturns the same value as function length • You must use dot notation in the call to function lengthor size
length method • no arguments, just () • smallest return possible is 0 (empty string) • treat return type as an integer • word = “Johnson” • x = word.length(); // gives x value 7
substr method • two arguments usually • example call: name.substr(4, 3) • first argument is position to start the string • Positionsof characters within a string arenumbered starting from 0, not 1 • second argument is how many characters • if second argument is omitted, means "until end of string" • returns a string (NOT a character)
find method • one argument • example call: name.find("Andy") • argument can be string or character • finds FIRST one from the left • case matters! • returns integer (actually size_t) • returns leftmost position found • or string::npos if not found
find method • Function find returns an unsigned integer value that is the beginning position for the first occurrence of a particular substring within the string • The substring argument can be a string constant, a string expression, or a char value • If the substring was not found, function find returns the special value string::npos
String Methods - Examples string street = "123 Main Street"; string number, st; // declarations int stlen, space_pos, x_pos; stlen = street.length(); // 15 space_pos = street.find (" "); // 3 x_pos = street.find ("x"); // npos number = street.substr(0,3); // "123" st = street.substr(9); // "Street"
Subscript notation • Another way to access individual elements of a string is with a subscript • If word = “joe”, then word[0] is ‘j’ • A character, not a smaller string • word[1] is ‘o’ and word[2] is ‘e’ • Be very careful about assigning string elements values like this – sometimes the length field is not correctly updated