C++ Lecture 4
[Previous Lecture]
[Lecture Index]
[Next Lecture]
Intro to Standard String Class
// Defines class string { ... };
#include <std/string.h>
- manages and manipulates strings of characters
(good replacement for the likes of
char buf[1024];)
- grows as needed
- has rich set of methods & overloaded operators
(i.e., strcpy(), strcmp(), etc.
no longer needed)
- can still get at C-style char * string if necessary.
#include <std/string.h>
int
main()
{
string s, t;
t = "hi";
t.append(" there");
cin >> s;
cout << t << ' ' << s << endl;
return 0;
}
More on Standard String Class
- string::size_type - type used to index characters
in a string
- string::npos - contsant size_type
that represents
- no possition (e.g., failure to find something)
- or `go to the end' (e.g., subtr() method)
- Commonly used string methods:
const char *c_str(): return C-style string
size_type length()
bool empty()
size_type find(char c, size_type n = 0);
size_type find(const string&, size_type n = 0);
string substr(size_type pos = 0,
size_type n = npos)
- Commonly used overloaded operators:
- == - contents of strings the same?
(also !=, <, <=, >=, >)
- = - assign a char *, char, or string
- += - append a char *, char, or string
- + - creates and returns a new string
- related functions:
- ostream& << string&
write a string
- istream& >> string&
read a (space delimited) string
- getline(istream&, string&, char delim='\n')
read a line (not including the \n)
[Previous Lecture]
[Lecture Index]
[Next Lecture]