C++ Strings and Functions


C++ Strings

C++ has a string class. Some functions are defined in the class for strings to use. In C++ programming, you can declare string variables/objects. A string may be declared with or without an initial value. If you do not indicate the initial value, the initial value is an empty string (zero length, no characters).
Here are some examples to help you understand C++ strings:


    //declare a string str1

    string str1; 

    //A string variable/object may be initialized with
    //a character string literal:

    string str2 = "Hello there";
    string str3 ("Goodbye");  // Alternate form 

    //A string variable/object may also be initialized with
    //a string expression:

    string str4 = str2;
    string str5 = str2 + str3;


    //A string variable/object may also be initialized with
    //a substring of another string object:

    string str6 = "ABCDEFGHIJKL";
    // Initialize str7 as "CDEFG"
    // Starts at character 2 ('C')
    // with a length of 5
    // (or the rest of the string, if shorter)
    string str7 (str6,2,5); 

 

The length( ) and size( ) Functions


	Both of these functions return the length 
	(number of characters) of the string.  
	The size_type return type is an unsigned integral 
	type.  We must use the qualified name as in 
	string::size_type because the definition of size_type 
	is otherwise hidden inside the definition 
	of the string type.

	string str8 = "Hello";
	string::size_type len;
	len = str8.length(); // len == 5 
	len = str8.size();   // len == 5

	or you can just use 

	cout << str8.length() << endl;
  

The find( ) and substr( ) Functions



	The find() function searches a string to find 
	the first occurence of a particular substring. 

	If found, return the position of the first character. 
	If not, return a special value (called string::npos).

	For Example:
	string str16 = "abcdefghi";
	string str17 = "def";

	// Search from the beginning of str16
	string::size_type pos = str16.find(str17,0);
	// Search from the beginning of str16
	string::size_type pos = str16.find(str17);
	// Search from the second character of str16
	string::size_type pos = str16.find(str17,1);

	// All above three ways return 3
	cout << pos << endl; // return 3

	pos = str16.find ("AB");
	if (pos == string::npos) 
		cout << "Not found " << endl;

	// substr( ) function will return a string
	// it has two parameters, one is the starting point
	// the other is the length of the substring to be obtained.
	// Here is the substr( ) function header line:

	string substr(size_type pos, size_type n);

	Returns a substring of the current string, 
	starting at position pos and of length n:

	string str18 = "abcdefghi"
	string str19 = str18.substr (6,2);
	cout << str19 << endl; // return "gh" 

Operators

A number of C++ operators also work with strings.

 



Back to the top


Copyright: Department of Computer Science, University of Regina.