Download presentation
Presentation is loading. Please wait.
1
Working with Strings Lecture 2 Hartmut Kaiser hkaiser@cct.lsu.edu
2
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 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?
3
C++ Libraries Groups related operations C++ Standard Libraries
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 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
4
String Input Given the following interaction: We would like to print:
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 String Input Given the following interaction: Please enter your name: John We would like to print: Hello John!
5
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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; }
6
String Input Place to put input into: variable
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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>
7
String Input Variable definition: std::string name;
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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
Names A name in a C++ program
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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
9
Names Choose meaningful names
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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
10
Framing a Name Given the following interaction:
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 Framing a Name Given the following interaction: Please enter your name: John We would like to print: ******************* * * * Hello John! *
11
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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; }
12
Framing a Name Variable definition Initialization
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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
13
Framing a Name Initializing using special constructor
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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.)
14
C++ std::string Models a sequence of characters
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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
15
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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; }
16
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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"; std::transform(s.begin(), s.end(), std::toupper); // converts to upper case std::cout << s << std::endl; // prints: CSC1254/1 return 0; }
17
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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; }
18
C++ std::string member functions
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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)
19
More String Details IO is using operator>> and operator<<
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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;
20
C++ strings vs. C strings
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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
21
C++ strings vs. C strings
CSC1254, Fall 2011, Strings 8/25/2011, Lecture 2 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';
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.