Presentation is loading. Please wait.

Presentation is loading. Please wait.

Working with Strings Lecture 2 Hartmut Kaiser

Similar presentations


Presentation on theme: "Working with Strings Lecture 2 Hartmut Kaiser"— Presentation transcript:

1 Working with Strings Lecture 2 Hartmut Kaiser hkaiser@cct.lsu.edu

2 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? 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

3 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 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

4 String Input Given the following interaction: We would like to print:
Please enter your name: John We would like to print: Hello John! 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

5 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; // define 'first_name' std::cin >> first_name; // read into 'first_name' // write a greating std::cout << "Hello, " << first_name << std::endl; return 0; } 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

6 String Input std::string 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> 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

7 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 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

8 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/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

9 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 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

10 Framing a Name Given the following interaction:
Please enter your name: John We would like to print: ******************* * * * Hello John! * 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

11 Framing a Name // Ask a persons name, greet the person #include <iostream> #include <string> int main() { std::cout << "Please enter your first name: "; // ask for the persons name std::string first_name; // define 'first_name' std::cin >> 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 << first << std::endl; return 0; } 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

12 Framing a Name Variable definition Initialization
Important! Use operator + for concatenation Custom operators do not change precedence, associativity, or number of arguments Constness Variable will not be changed Requires initialization 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

13 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.) 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

14 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 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

15 C++ std::string #include <iostream> // std::cout, std::endl #include <string> // 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; // prints: 'hello jello' return 0; } 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

16 C++ std::string #include <iostream> // std::cout, std::endl #include <string> // std::string #include <cctype> // std::toupper #include <algorithm> // std::transform int main() { std::string s; s = "csc1254/1"; // converts to upper case std::transform(s.begin(), s.end(), s.begin(), std::toupper); std::cout << s << std::endl; // prints: CSC1254/1 return 0; } 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

17 C++ std::string #include <iostream> // std::cout, std::endl #include <string> // std::string #include <algorithm> // std::sort int main() { std::string s; s = "hello John"; std::sort(s.begin(), s.end()); // sort all characters of the string std::cout << s << std::endl; // prints: ' ehhllooJ' return 0; } 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

18 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) 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

19 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; 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

20 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 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings

21 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"; // won't compile "abc" + 'd'; // will compile, but do wrong // thing Can force conversion if needed std::string("abc") + 'd'; 8/29/2013, Lecture 2 CSC1254, Fall 2013, Strings


Download ppt "Working with Strings Lecture 2 Hartmut Kaiser"

Similar presentations


Ads by Google