C++
strings
You have a
string class available to you in C++ and can access it using
#include<string> (Note that it is not <cstring>. cstring
is for C style strings which are different as follows:
C string - null
terminated
C++ string - not
null terminated. they contain…
pointer to character
array
length of string
(properties same as what we have been doing
Note that when
you declare a C++ string you use all lowercase characters ( string NOT String
).
There are many
things you can do with C++ strings. For example:
Declaration and Assignment
examples:
string s;
//
empty string with length of 0
string s1 = "Hello"; // can initialize as array
of characters
string s2 = s1; //
can initialize to another string
comparison
operators ( ==, !=, <, >, <=, >= ). All will return
bool.
examples:
string s3;
cin
>> s3;
if
(s3 == "sort")
…do sort routine
else if (s3 == "print")
… do print routine
Multiple
Constructors available
examples:
string s4(7,'a');
//
makes string = "aaaaaaa"
string s5 = "Frodo";
// uses C style
string
string s6 = s5;
string s7(s5, 3, 2);
// result will be
"do"
s7 will use s5,
starts at element 3, goes length of 2. Remember - always use
zero based indexing
so just remember
( source, starting point, number of
positions)
char msg[] = "This is fun!";
string s8(msg+5, 2);
// result is
"is"
string s9(msg, 5, 3); // essentially the same
thing
they will point
to the 5th position of msg ("i") and take two characters
("is")
This idea of two
integer arguments ( position and length ) is common in C++ strings but beware!
This is a common source of errors.
operator
=
examples:
string s1,s2;
s1
= s2;
s1
= "second"; // converts C style string to C++
string
s1
= 'a'
//
this will convert character to C++ string
//
because s1 is already declared
BUT…
string s3 = 'b'; // ERROR - can't declare and
initialize this way
string
class functions:
.c_str(
)
Takes no
arguments and returns a pointer to a C style string. It enables you to
access characters in a data array and change them. The best way to use
this is when you need to read, like using atof…
example:
string s4 = "123.4";
cout << atof(s4.c_str());
This takes s4
and converts it to a C style string and passes it back to atof which converts it
to a float which can then be used in calculations.
operator[
]
example
s4[1]
//
will return character #1 ("2")
s1[0] = 'X' // can do but be careful with
[]
There are two
forms of subscript overloading same as in the class we wrote so just use them
whenever you normally would
operator
+
you can use
for:
string + char
string + string
string += char
string += string
.append(
char ) or .append( string )
This will append
to the end of a string. Use as follows:
string s4 = "zig";
s4.append("zag");
// will give you "zig
zag"
.insert(
int, string)
can have many
forms. It allows you to place other strings anywhere inside a string. It
has the form:
.insert(int position, string)
Note: position - start inserting BEFORE this
integer position
forms of the
.insert function:
.insert(int pos, string);
//
inserts all of string
.insert(int pos, string, int, int) //from string,
starting..., for …chars
.insert(int pos, char *)
//
inserts C style string
.insert(int pos, char* int)
//
int chars of C style string
examples of
.insert
string s1 = "hot dog";
s1.insert(4, "diggety");
cout << s1;
// yields - hot diggety
dog
string s2 = "slam";
string s3 = "grand";
s2.insert(0, s3);
// will make "grand
slam"
s2.insert(0, s3, 2, 4); // makes
"and grand slam"
.replace
We can also
replace substrings within strings (like changing a name in a message that goes
out to several people)
.replace(position, length, replace_with)
you can use a C
style string or C++ string in the replace. It will adjust the string for
different length of replacement.
examples of .replace
string s5 = "High dive!";
s5.replace(5, 4, "jump");
//
"High jump!"
s5.replace(5, 4, "interest rate"); // "High
interest rate!"
s5.replace(5, 4, "sky");
//
"High sky!"
.erase(pos, len)
Will erase a
given number of characters starting at assigned location and adjust length of
the string
.erase(position, length);
so
now…
s5.erase(5, 4); //
"High !"
.find(string)
Returns an
integer indicating location of the first occurrence of a string.
examples:
s6
= "Ooga Booga";
s6.find("Boo"); //
will return 5 (case matters!!)
s6.find("Book", 3, 1);
this will search
using the 3rd position of Book for length of 1 character
("k") and will exit when not found.
.length(
) and .size( )
Both functions
do the same thing and return an integer which is the length of the
string.
.rfind(string)
Does the same as
find except it will start from the end of the string and search
backwards.
example:
string s7 = "High road";
s7.rfind("gh") //
returns 2 as the position
This is useful
if…
string s8 = "www.cs.niu.edu";
int
p = s8.rfind('.'); // will find the last period and
returns value 10
then you can
use…
s8.replace(p+1, 3, "com"); // makes
"www.cs.niu.com"
You could also
code:
s8.replace(s8.rfind('.')+1, 3, "com");
The second way
works but is not a good idea. You can get into trouble because order of
evaluation is not portable. It may work on the machine you write the code
on and not the machine you implement it on. If you don't find '.' on
the second way you will get a bogus position so it's best to split up the
function calls and always do error checking.
.empty(
)
This function
will takes no arguments and returns a bool indicating if the string is empty or
not.
.substr(
)
takes an integer
indicating position and a length of characters and returns a string. It is
used to extract a substring within a string.
example:
string s1 = "submarine";
string s2;
s2
= s1.substr(3,3); // this
extracts "mar"
additional
information:
you can also use
cout << s4 and cin >> s4 with C++
strings
|