working with strings lecture 2 hartmut kaiser [email protected]

21
Working with Strings Lecture 2 Hartmut Kaiser [email protected] http://www.cct.lsu.edu/˜hkaiser/spring_2015/csc1254.html

Upload: dominick-hicks

Post on 28-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Working with StringsLecture 2

Hartmut Kaiser

[email protected]

http://www.cct.lsu.edu/˜hkaiser/spring_2015/csc1254.html

CSC

1254,

Spri

ng 2

015,

Str

ings

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?

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

4

String Input•Given the following interaction:

Please enter your name: John

•We would like to print:

Hello John!

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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;}

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

6

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

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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_sumelement_countstaple_partition

Too long: the_number_of_elements

remaining_free_slots_in_the_symbol_table

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

10

Framing a Name•Given the following interaction:

Please enter your name: John

•We would like to print:

******************** ** Hello John! ** ********************

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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 << second << std::endl; std::cout << first << std::endl; return 0;}

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

12

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

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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.)

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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 charsoperator[] to access individual characters C++ strings are mutable

•Operators on stringsoperator= assigns, makes new copy Compare with relational operators: <, <=, ==, >=, >

Lexicographical orderingoperator+ concatenates

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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;}

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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(std::begin(s), std::end(s), std::begin(s), std::toupper);

std::cout << s << std::endl; // prints: CSC1254/1 return 0;}

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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";

// sort all characters of the string std::sort(std::begin(s), std::end(s));

std::cout << s << std::endl; // prints: ' Jehhllnoo' return 0;}

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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 posstd::string substr(int pos, int len)

Changes string, inserts txt at posvoid insert(int pos, std::string txt)

Changes string, removes len characters starting at posvoid erase(int pos, int len)

Changes string, removes len characters starting at pos, inserts txt

void replace(int pos, int len, std::string txt)

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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;

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

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

1/2

0/2

015,

Lect

ure

2

CSC

1254,

Spri

ng 2

015,

Str

ings

21

C++ strings vs. C strings•Concatenation pitfalls

If one operand is a C++ string, all is goodstd::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 neededstd::string("abc") + 'd';

1/2

0/2

015,

Lect

ure

2