Working with Strings Lecture 2 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/spring_2015/csc1254.html
Abstract This lecture will look at strings. What are strings? How can we input/output strings? How can we manipulate strings? What functionality is provided by the std::string type? 2
C++ Libraries Groups related operations Header file provides function prototypes and usage comments Compiled library contains implementation C++ Standard Libraries E.g. string, iostream, fstream #include <foo> Terse lowercase names: cout, getline, substr 3
String Input Given the following interaction: Please enter your name: John We would like to print: Hello John! 4
String Input // Ask a persons name, greet the person #include <iostream> #include <string> int main() { // ask for the persons name std::cout << "Please enter your first name: "; // read the name std::string first_name; std::cin >> first_name; // define 'first_name' // read into 'first_name' } // write a greating std::cout << "Hello, " << first_name << std::endl; return 0; 5
String Input Place to put input into: variable Variables are objects which have a name (first_name) Objects are part of the computer memory with an associated type (std::string) std::string Part of namespace std #include <string> Powerful data type conveniently enabling string manipulations 6
String Input Variable definition: std::string name; Local variable, is destroyed at end of block Type defines the available operations and interface exposed by the object Initialization, here: empty (or null) string String input using operator >> from std::cin Discards leading whitespace Stops at whitespace Input/output buffering occurs flushing is performed: buffer full, input, explicit request 7
Names A name in a C++ program Starts with a letter, contains letters, digits, and underscores (only) x, number_of_elements, Fourier_transform, z2 Not names: 12x time$to$market main line Do not start names with underscores: _foo those are reserved for implementation and system entities Users can't define names that are taken as keywords E.g.: int return while double 8
Names Choose meaningful names Abbreviations and acronyms can confuse people mtbf, TLA, myw, nbv, wtf Short names can be meaningful when used conventionally: x is a local variable i is a loop index Don't use overly long names Ok: partial_sum element_count staple_partition Too long: the_number_of_elements remaining_free_slots_in_the_symbol_table 9
Framing a Name Given the following interaction: Please enter your name: John We would like to print: ******************* * * * Hello John! * * * ******************* 10
Framing a Name // Ask a persons name, greet the person #include <iostream> #include <string> int main() { std::cout << "Please enter your first name: "; std::string first_name; std::cin >> first_name; // ask for the persons name // define 'first_name' // read into 'first_name' } std::string const greeting = "Hello, " + first_name + "!"; // build the message we intend to write std::string const spaces(greeting.size(), ' '); // build the second and fourth string std::string const second = "* " + spaces + " *"; std::string const first(second.size(), '*'); // build the first and fifth lines std::cout << first << std::endl; // write all std::cout << second << std::endl; std::cout << "* " + greeting + " *" << std::endl; std::cout << second << std::endl; std::cout << first << std::endl; return 0; 11
Framing a Name Variable definition Initialization Important! Use operator + for concatenation Custom operators do not change precedence, associativity, or number of arguments Constness (keyword const) Variable will not be changed Requires initialization May allows for more optimizations Expresses intention to the compiler 12
Framing a Name Initializing using special constructor std::string spaces(greeting.size(), ' '); Number of characters and character literal (' ') Quoting similar to string literals ('\t', etc.) 13
C++ std::string Models a sequence of characters std::string is defined as class (user defined) type Simple operations Member function size() returns number of chars operator[] to access individual characters C++ strings are mutable Operators on strings operator= assigns, makes new copy Compare with relational operators: <, <=, ==, >=, > Lexicographical ordering operator+ concatenates 14
C++ std::string #include <iostream> #include <string> // std::cout, std::endl // std::string int main() { std::string s, t = "hello"; s = t; // s == "hello" std::cout << "Length: " << s.size() << std::endl; t[0] = 'j'; // t == "jello" s = s + ' '; // s == "hello " s += t; } std::cout << s << std::endl; return 0; // prints: 'hello jello' 15
C++ std::string #include <iostream> #include <string> #include <cctype> #include <algorithm> // std::cout, std::endl // std::string // std::toupper // std::transform int main() { std::string s; s = "csc1254/1"; // converts to upper case std::transform(std::begin(s), std::end(s), std::begin(s), std::toupper); } std::cout << s << std::endl; return 0; // prints: CSC1254/1 16
C++ std::string #include <iostream> #include <string> #include <algorithm> // std::cout, std::endl // std::string // std::sort int main() { std::string s; s = "hello John"; // sort all characters of the string std::sort(std::begin(s), std::end(s)); } std::cout << s << std::endl; return 0; // prints: ' Jehhllnoo' 17
C++ std::string member functions Invoke member functions as: str.function(args) Sample member functions: Return index of first occurrence or std::string::npos int find(char c, int pos) int find(std::string pattern, int pos) Return new string, copies len characters starting at pos std::string substr(int pos, int len) Changes string, inserts txt at pos void insert(int pos, std::string txt) Changes string, removes len characters starting at pos void erase(int pos, int len) Changes string, removes len characters starting at pos, inserts txt void replace(int pos, int len, std::string txt) 18
More String Details IO is using operator>> and operator<< os << s: output s to stream os without formatting changes evaluates to os is >> s: input s from stream is with whitespace handling evaluates to is Ways to initialize: std::string hello = "hello"; std::string stars(10, '*'); std::string name; 19
C++ strings vs. C strings C++ inherits legacy of old-style C string String literals are actually C strings (pointer to array of null terminated characters) Converting C string to C++ string Happens automatically in most cases Can be forced: std::string("abc") Converting C++ string to C string Using member function s.c_str() Why do we care Some older functionality requires use of C strings C strings are not compatible with concatenation 20
C++ strings vs. C strings Concatenation pitfalls If one operand is a C++ string, all is good std::string str = "Hello "; str = str + "John"; str = str + '!'; If both operands are C strings/characters, bad times "abc" + "def"; "abc" + 'd'; // won't compile // will compile, but do wrong // thing Can force conversion if needed std::string("abc") + 'd'; 21