Lecture Notes for Introduction to Computer Science II
24 May 2001 - The String Data Type
- character arrays and strings
- character arrays -
char name[32];
- character arrays contain strings
- sequence of characters
- terminating 0 (or null) byte - important
- literals -
"hello world!"
- good - fairly efficient, fits with the rest of c++
- bad - arrays are dangerous; strings are clumsy; the combination of
arrays and strings are deadly
- arrays are dangerous because the array bounds are not checked and
they have fixed size
-
char name[10];
name[-100] = 'a';
name[100] = 'a';
- the problem need not be severe -
name[10] = \0;''
- strings are clumsy because of the null byte, subroutine
manipulations, and comparisons
- arrays and strings are deadly because
- strings can overflow arrays with no warning
- dynamic strings and static arrays
- the null byte is often forgotten
- do not use character arrays - they are hard to work with and dangerous
- sometimes you have to - command-line arguments; system call arguments
- what to use instead - the c++ standard string data type
- get the terminology straight - character arrays vs. strings
- strings are defined in the header file
string
- note the absence of the
.h
- string.h
is something
completely different
- why strings are better than character arrays
- strings don't have a null byte - nothing to forget, nothing to
remember
- strings manage space themselves - no overflows
- comparisons work as expected
- string declarations and initialization
- use
#include <string>
to get access to strings
- part of the standard c++ library - need the
std::
prefix
- use the
using std::string;
statement to forego the
std::
prefix
- strings can be initialized in the usual way
-
std::string name = "jacaranda";
- a string with no initialization is the empty string - the string
with no characters
- strings are accessed with subscripts, just like arrays
- the index range is the same
- the
length()
function returns the number of characters in a
string
- unfortunately, subscript access to strings is not checked
- the
at()
accessor is checked
- string assignment and access
- assignment behaves like normal
- strings are accessed with subscripts, just like arrays
- unfortunately, subscript access to strings is not checked
- the
at()
accessor is checked
-
+
does string catenation
- string comparison
==
works as expected
- stream io operations
-
>>
and <<
work as expected - eats white space
-
str::string name;
cin >> name;
- the
getline()
function doesn't eat white space
- strings and character arrays
- automatic (mostly) conversion from character arrays to strings
- conversion from strings to character arrays is not automatic, but
it is possible
- characters are not character arrays - conversions between
a character and a string requires work
This page last modified on 29 May 2001.