[Skip Navigation] [CSUSB] / [CNS] / [CSE] / [R J Botting] / [CSE201] / string
[Text Version] [Syllabus] [Schedule] [Glossary] [Labs] [Projects] [Resources] [Grading] [Contact] [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]
Tue Apr 9 09:37:19 PDT 2013

Contents


    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");

      Accessing data about a string == length and empty

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

      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";
      then
       		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 -- substr

      This
         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)" because I started counting the characters with "1" not "0". Look out for this "off by one" error.

      There is a useful abbreviated version of substr with only one explicit parameter:

       	string("example").substr(2)
      is string("ample") because it is the string starting at character 2 in "example" and ending at the end of the string. As a rule
    1. s.substr(i) is a short form of
    2. s.substr(i, s.length()-1). for any string s.

      Searching for a substring -- find

      There are many different ways of searching a string for a substring. The simplest is find.
       	string("example").find("e")
      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.

      Comparisons

      Lexographic/alphabetical) -- same syntax as for ints and doubles.
          s1 == s2
          s1 != s2
          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

       	cin >> word;

      Input strings

       	getline (cin, line);

      Output strings

       	cout << stringexpression ...

      Working on a character in a string

      If s is a string and i is an positive interger that is less than s.lenght() then
       	s[i]
      is a character in the string and
       	s.substr(i,1)
      is a string containing the i'th character in s.

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

       		string example="example";
       		example[1]
      is 'x' not 'e'. And
       		example[0]
      is '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 [ back.cpp ]

      Exercise: can you rewrite 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 [ 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 [ stringnumbers.cpp ] is a program that demonstrates how to use a couple of functions "convertDouble" and "convertToDouble" that are defined in [ 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

      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. [ Widget.h ] [ listWidgets.cpp ]

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

    Abbreviations

  1. Algorithm::=A precise description of a series of steps to attain a goal, [ Algorithm ] (Wikipedia).
  2. Class::=A description of a type of object that includes the data it knows and the functions it can execute.
  3. Function::programming=A selfcontained and named piece of program that knows how to do something.
  4. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular and free C++ compiler.
  5. OOP::="Object-Oriented Programming", Current paradigm for programming.
  6. Semantics::=Rules determining the meaning of correct statements in a language.
  7. SP::="Structured Programming", a previous paradigm for programming.
  8. Syntax::=The rules determining the correctness and structure of statements in a language, grammar.
  9. Q::software="A program I wrote to make software easier to develop",
  10. TBA::="To Be Announced", something I should do.
  11. TBD::="To Be Done", something you have to do.
  12. UML::="Unified Modeling Language", industry standard design and documentation diagrams.
  13. void::C++Keyword="Indicates a function that has no return value".

( End of document ) <<Contents | Top