0% found this document useful (0 votes)
65 views

C++ Programming TI00AA50: Jarkko - Vuori@metropolia - Fi

This document provides an overview of the C++ standard library class string. It discusses how string handles memory allocation dynamically and implements operators and functions to manipulate strings. Key points include: string stores characters in dynamically allocated memory unlike C-style strings; the standard library includes a pre-defined string class that handles operations like assignment, comparison, concatenation and input/output; and functions are provided to access characters, find substrings, and manipulate the size and capacity of strings.

Uploaded by

inuyashahot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

C++ Programming TI00AA50: Jarkko - Vuori@metropolia - Fi

This document provides an overview of the C++ standard library class string. It discusses how string handles memory allocation dynamically and implements operators and functions to manipulate strings. Key points include: string stores characters in dynamically allocated memory unlike C-style strings; the standard library includes a pre-defined string class that handles operations like assignment, comparison, concatenation and input/output; and functions are provided to access characters, find substrings, and manipulate the size and capacity of strings.

Uploaded by

inuyashahot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

C++ Programming

TI00AA50
Lecture 5 - 08.10.2015

[email protected]

Class string

In C-language a character array with terminating zero is used as a string

There are many disadvantages in C-like strings:

C-library contains many string manipulation functions (string.h)


They can not be assigned with assignment operator
They can not be compared with comparison operators
They cannot expand automatically
Etc.

h e l

o 0

After we have learned the basics of classes, we would be able to define a class string
for example in the following way and implement its operation functions:
class string {
public:
string(const char *string0="");
string operator+(const string &s2) const;
const string &operator=(const string &right);
//and many other operators and member functions
private:
char *c_string;
};

But it is not necessary to implement it ourselves, because it has been done already in
the C++ standard library. We only have to include the header file and use it
#include <string>
TI00AA50/JV

String example

Advantages:
You dont have to give
the length in the
declaration
Memory area expands
automatically
Assignment works (it is a
real deep copy)
Comparison can be done
with comparison operator
(means alphabetical
order)
Input (>>) and output
(<<) operators are
defined for string

#include <iostream>
#include <string>
using namespace std;
void main() {
string str1, str2;
cout << "\nEnter a string";
cin >> str1;
str2 = str1; //assignment is OK
cout << "\nCopy of string 1 is : " << str2;
cout << "\nEnter a string";
cin >> str2;
if (str1 < str2) //comparison is OK
cout << str1 << "is less than" << str2 ;
else
cout << str2 << "is > or equal to" << str1 ;
cout << "\nThe capacity of the str2 is " <<
str2.capacity();
cout << "\nThe size (length) of the str2 is " <<
str2.size();
}

TI00AA50/JV

Basic operations of string

Actually string is instantiated from the


class template basic_string in the
following way:

Input and output operators are defined

typedef basic_string<char> string;

cout << s1; //display a string


cin >> s1; //input is delimited by
white space
getline(cin, s2); //read a whole line

(we will learn about class templates later)

Constructors

More about assignment (two


expressions below are the same):

string s1; //default


string s2("abcdefg"); //initialising
with c-string
string s3(10, A); //initialising with
n characters

Assignment operator
s1 = "abcde";// assigning a c-string
s2 = X;
// assigning a character
s3 = s1;
// assigning another string

s1 = s2;
s1.assign(s2);

Accessing individual characters


(indexing and at member function):
char chr;
chr
=
s1[i]
=
chr
=
s1.at(i) =

TI00AA50/JV

s1[i];
X;
s1.at(i);
X;

// right val
// left val
// right val
//
--

Concatenation and comparison

Concatenation

String comparisons

string s1("Helsinki ");


string s2("Metropolia ");
string s3("University of Applied Science");
string s4;
s4 = s1 + s2;
s1 += s2;
s1.append(s2);
s4 = s4.append(s3, 0, 10); // Append
substring of s3

start

Operators ==, !=, <, <=, >, >= (return value


bool)
Member function compare (return value <0,
0, or >0 as from strcmp)
if (s1.compare(s2) == 0)
cout << "Strings are identical";

Comparing substring with overloaded


functions
if(!s1.compare(2, 5, s2, 10, 5)) {
cout << "Strings s1 and s2
contain same";
cout << " substring of 5
characters";
cout << "starting at character
position 2";
cout <<" in s1 and character
position 10 in s2";
}

length

Note that the first position is 0

TI00AA50/JV

Substrings, size, length and


capacity

Taking substrings
string s1("Helsinki Metropolia University");
string s2, s3;
s2 = s1.substr(0, 8);
//Helsinki
s3 = s1.substr(9, 10);
//Metropolia

Swapping strings
string s1("Espoo");
string s2("Helsinki");
s1.swap(s2); //s1 contains Helsinki and
s2 Espoo

string s1;
cout << s1.size() << s1.length()
s1 = "abcdef";
cout << s1.size() << s1.length()
s1.resize(s1.size() + 5);
cout << s1.size() << s1.length()
s1.reserve(30);
cout << s1.size() << s1.length()

<< s1.capacity();
<< s1.capacity();
<< s1.capacity();
<< s1.capacity();

Member functions length, size, capacity


and max_size

length and size return the number of


characters of the string currently stored in
string
capacity returns the number of characters
that can be stored in the string without
reallocation
max_size returns the absolute upper limit
for the size of string in the current
environment (Visual Studio 2010 has
max_size of 232-2)
TI00AA50/JV

Allocation policy

As we saw in the
previous page, the size
(length) of the string can
be different from the
capacity
The memory allocation
policy can be different in
different systems but the
following example gives
an idea of how it could
work (this is the case in
Visual Studio 2010)

Example.
string s;
s = "abcd";
s.reserve(8);
s = s + "efg";
s = s + "hij";
s.resize(14);
s.reserve(20);
s.resize(17)

Size
// 0
// 4
// 4
// 7
// 10
// 14
// 14
// 17

Capacity
15
15
15
15
15
15
31
31

Contents
Empty
|abcd|
|abcd|
|abcdefg|
|abcdefghij|
|abcdefghij|
|abcdefghij...|
|abcdefghij...|

represents a space in the example above

TI00AA50/JV

Find and replace

Finding substrings and characters


01234567890123456789012345
string s1("xxcxxxabcxxxxxxxxabcxxxxxx");
int pos;
pos = s1.find("abc");
// 6 (find string "abc")
pos = s1.rfind("abc");
//17 (reverse find)
pos = s1.find_first_of("abc");
// 2 (find one char)
pos = s1.find_last_of("abc");
//19 (reverse find)
pos = s1.find_first_not_of("xac"); // 7 (find one char)
pos = s1.find_last_not_of("xac"); //18 (reverse find)

The return value of find is string::npos if not found


Replacing substrings and characters
string s1("Espoo-Vantaa Institute of Technology");
s1.erase(5);
//Espoo
string s2("xxxxxyyyxxxxxxxxxxx");
s2.replace(5, 3, "abc");
//xxxxxabcxxxxxxxxxxx
s2.replace(5, 3, "abcedfYYYghi", 6, 3); //xxxxxYYYxxxxxxxxxxx

TI00AA50/JV

Inserting and Conversions

Inserting strings
string s1("Espoo Institute of Technology");
string s2("xxxxxVantaayyyyy");
//s1.insert(5, "-Vantaa");
//Espoo-Vantaa Institute of ..
s1.insert(5, "-").insert(6, s2, 5, 6); //----

Conversions to C-string (member functions copy, data and c_str)


copy
size_t copy(char *cb, size_t n, size_t pos = 0);
Function copies from the C++ string to the C character array. You need to add
terminating zero yourself
Data
const char *data() const;

c_str
const char *c_str() const;

TI00AA50/JV

String streams and iterators

String streams

In memory I/O
Include files iostream and sstream are
needed
Classes istringstream and
ostringstream
Member function str of ostringstream
Connecting buffer or not connecting
memory buffer
C++-style or C-style string buffer
See example on the right

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
// This program demonstrates how to use string
// streams to make conversions from numbers to
// strings and vice versa
int main() {
{ // Convert a number to string
string num_str;
int num_int = 127;
ostringstream string_stream;
string_stream << num_int;
num_str = string_stream.str(); // now we have it
cout << num_str;
// as a string
}
{ // Convert a string to the number
string num_str("127");
int num_int;
istringstream string_stream(num_str);
string_stream >> num_int;
// now we have it
cout << num_int;
// as int
}

Iterators (to be discussed later)

class string::const_iterator;
string member functions begin and
end;
iterator comparison operators
dereference operator
increment operators
string::reverse_iterator
string::const_reverse_iterator

TI00AA50/JV

10

String streams

We have used input streams to read information from the keyboard and
output streams to display information

Input stream and output stream make conversions as we see in the following example
int a = 127; double b;
cout << a; // conversion is done from int to chars
cin >> b; // conversion is done from chars to double

When we write (<<) information to the stream cout, it goes to the display
When we read (>>) information from the stream cin it comes from the
keyboard
In the lab exercises 5 well see that we can connect a stream to the disk file
ofstream output_file("file.txt");
ifstream input_file("file.txt");

It is also possible to specify a stream that contains a string

In this case when we write data to the stream it goes to the string and when we read the
stream, data comes from the string
This is useful when we need to make conversions
See an example program in the following page
TI00AA50/JV

11

Streams to/from different destinations in C and C++


C

C++

1. Stream to the console screen and keyboard


(or more generally to any device)
int a = 10; float b = 100.5;
printf(%d %f, a, b);
stdin and stdout
scanf(%d%f, &a, &b);

1. Stream to the console screen and keyboard


(or more generally to any device)
int a = 10; float b = 100.5;
cin and cout
cout << a << b;
cin >> a >> b;
Linux:
//dev//tty
2. Stream to the file
Windows:
int a = 10; float b = 100.5;
CON:
ofstream output_file(file.txt);
output_file << a << << b;

Linux:
//dev//tty
Windows:
CON:
output_file = fopen(file.txt, w);
fprintf(output_file, %d %f, a, b);
fclose(output_file);

2. Stream to the file


int a = 10; float b = 100.5;
FILE *input_file, *output_file;

input_file = fopen(file.txt, r);


fscanf(input_file, %d%f, &a, &b);
fclose(input_file);
3. Stream to the string
int a = 10; float b = 100.5;
char mystring[20];
sprintf(mystring, %d %f, a, b);
sscanf(mystring, %d%f, &a, &b);

ifstream input_file(file.txt);
input_file >> a >> b;
3. Stream to the string
int a = 10; float b = 100.5;
string mystring;
ostringstream string_stream;
string_stream << a << << b;
mystring = string_stream.str();

istringstream string_stream(mystring);
TI00AA50/JVstring_stream >> a >> b;

12

Stream formatting

Stream manipulators are functions specifically


designed to be used in conjunction with the
insertion (<<) and extraction (>>) operators on
stream objects, for example:
cout << boolalpha;

They are still regular functions and can also be


called as any other function using a stream
object as argument, for example:
boolalpha(cout);

Manipulators are used to change formatting


parameters on streams and to insert or extract
certain special characters
Iosmanip contain usefull manipulators for
input/output stream formatting, e.g.

setiosflag() sets the format flags specified


setfill() sets c as the stream's fill character
(to fill field to the given width)
setw() sets the field width to be used on output
operations
TI00AA50/JV

#include <iostream>
#include <iomanip>
using namespace std;
class Time {
friend ostream& operator<<(ostream &out, Time time);
private:
int hour, min;
public:
Time(int hour = 0, int min = 0) {
this->hour = hour;
this->min = min;
}
};
ostream& operator<<(ostream &out, Time time) {
out << setiosflags(ios::right);
out << setfill('0') << setw(2) << time.hour;
out << ":" << setfill('0') << setw(2) << time.min;
return out;
}
void main() {
Time t1(11,1), t2(2,30);
cout << t1 << endl;
cout << t2 << endl;
}

13

You might also like