[Skip Navigation] [CSUSB] / [CNS] / [Comp Sci & Eng Dept] / [R J Botting] / [CSci202] / string
[Text Version] [Syllabus] [Schedule] [Glossary] [Resources] [Grading] [Contact] [Question] [Search ]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Labs: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10]
Wed May 13 17:01:26 PDT 2009


    The C++ Standard string library

      C++ has a powerful and useful class of objects in its library. They are called strings. They contain characters. You can use them to model words and character data. They can contain any characters or no characters. They can change size as you need. You can input them and output them. You can also "slice and dice" them.

      The characters in a string are numbered, starting at 0 -- don't ask why!

      So string("12345") has the character "1" in place 0, "2" in place 1, and so on.

      These notes give a simplified description of the ways they can be used.

      Include this library

      The easy way to use strings is to put these lines at the start of your program
       #include <string>
       using namespace std;

      Declaring a string variable

       string newVariable = "initial value";
       string newVariable = anyStringExpression;

      Constructing a C++ string from a litteral

       		string ("example");

      This is also use to construct a C++ string from an old C char*:

       		char * cp = "example";
       		string (cp);

      Accessing data about a string == length and empty

      If you have a string called s then
      is the number of characters in the string, and
      is true if the string is empty. So, for example,
      has value 7.

      Accessing the old-style C char* in a string

      This expression gives you the array of chars, terminated by a null '\0' char:

      Concatenating two or more strings

      You can use the "+" symbol to combine strings. For example, if we declare
       		string a = "abra";
       		string b = "ca";
       		string c = "dabra";
       		cout << a + b + c <<endl;
      outputs "abracadabra". Notice you have to have at least one string variable or explicitly convert a old-style C string like "abra" into a modern string:
       		cout << string("abra") + "ca" + "dabra" <<endl;
      otherwise C++ has problems with it.

      Copying and assigning strings

      The normal assignment (=) works with strings.

      Extracting substrings

         string substr (int position, int length)
      extracts a substring. So
         string("example").substr (0, 4)
      is string("exam") and
         string("example"). substr (6, 1)
      is string("e").

      By the way.... i first wrote "substr(7,1)" becasue I started counting the characters with "1" not "0". Look out for this "off by one" error.

      Searching for a substring

      There are many different ways of searching a string for a substring. The simplest is find.
      has value 0 (the place of the first "e", and
       	string("example").find("e", 1)
      has value 6 -- the next "e" starting from the "x".

         int find (substring)
         int find (substring, startingPoint)

      If a matching substring is not found "find()" returns string::npos which is a value that is never the palce of a substring in a string.


      Lexographic/alphabetical) -- same syntax as for ints and doubles.
          s1 == s2
          s1 != s2
          s1 < s2
          s1 > s2

      Again one of the strings must be modern C++ string. "bad" < "cad" does not compare the contents of the literals.

      Input words into a string

      This stops at the first whitespace character but does not store it.
       	cin >> word;

      Input lines into a string

      Use getline like this
       	getline (cin, line);
      This works with all input streams.

      Output strings

       	cout << stringexpression ...

      Working on a character in a string

      If s is a string and i is an positive integer that is less than s.lenght() then
      is a character in the string and
      is a string containing the i'th character in s.

      Note: the characters are numbered 0,1,2,3,..... For example,

       		string example="example";
      is 'x' not 'e'. Similarly example[6] is an 'e' and the last valid character.

      Warning: bad things happen if you go outsude the range 0,1,2,.... ,length()-1.

      Single characters are typed with single quotes

      For historical reasons, 'x' is a character and "x" is a string of two characters!

      Working on each character in a string in turn

      Use a for loop. Here is an example, that replaces each 'a' in a string s by 1:
       		for(int i = 0; i < s.length(); i++)
       			if( s[i] == 'a' )
       				s[i] = '1';

      Here is a way to use a for loop to output a string backwards

       		for(int i = 0; i < s.length(); i++)
       			cout << s[s.length()-i-1];
      Exercise: try running this fragment by hand with string("abcd").

      I tested the code in [ ../cs201/back.cpp ]

      Exercis: can you right the for loop that starts at the end of the string and works back to 0 (and no further)?

      Inputting one character at a time

      You can read data from input one character at a time and put it in a string if you want. Here is a sample [ ../cs201/backwards.cpp ] of using cin.get(c).

      How can I convert numbers to strings and strings to numbers

      I've dug up a couple of advanced types of objects "stringstreams" that do the job if you need it in a project, for example. Here [ ../cs201/stringnumbers.cpp ] is a program that demonstrates how to use a couple of functions "convertDouble" and "convertToDouble" that are defined in [ ../cs201/stringnumbers.h ] that you can download and #include in any of your programs.
       string convertDouble(double d)
       	std::ostringstream s;
       	s << d;
       	return s.str();
       double convertToDouble(string d)
       	double result;
       	std::istringstream s(d);
       	s >> result;
       	return result;


      Stringstreams are a very powerful feature. Suppose you have a line that describes a person. It has the first name, their second name, there phone number, and their age. Each is a field with no spaces. Between them is one or more spaces:
       		John Doe 909-883-1234 31
       		Jane Row 714-123-4567 21
      Then we can write:
       		string line;
       		string first, second, phone; int age;
       		getline(input, line);
       		std::istringstream data(line);
       		data >> first >> second >> phone >> age;
      to unpack the data.

      KISS file handling

      Here is an example of the kind of simple code you can use that combines stringstreams, objects, etc. [ ../cs201/Widget.h ] [ ../cs201/listWidgets.cpp ]

    . . . . . . . . . ( end of section The C++ Standard string library) <<Contents | End>>


  1. Algorithm::=A precise description of a series of steps to attain a goal, [ Algorithm ] (Wikipedia).
  2. class::="A description of a set of similar objects that have similar data plus the functions needed to manipulate the data".
  3. Data_Structure::=A small data base.
  4. Function::programming=A selfcontained and named piece of program that knows how to do something.
  5. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular and free C++ compiler.
  6. KDE::="Kommon Desktop Environment".
  7. object::="A little bit of knowledge -- some data and some know how", and instance of a class".
  8. OOP::="Object-Oriented Programming", Current paradigm for programming.
  9. Semantics::=Rules determining the meaning of correct statements in a language.
  10. SP::="Structured Programming", a previous paradigm for programming.
  11. STL::="The standard C++ library of classes and functions" -- also called the "Standard Template Library" because many of the classes and functions will work with any kind of data.
  12. Syntax::=The rules determining the correctness and structure of statements in a language, grammar.
  13. Q::software="A program I wrote to make software easier to develop",
  14. TBA::="To Be Announced", something I should do.
  15. TBD::="To Be Done", something you have to do.
  16. UML::="Unified Modeling Language".
  17. void::C++Keyword="Indicates a function that has no return".