CS115 Lab: C++ Strings

In this lab,  you will learn how to manipulate strings.

Lab Exercise:


Click the little computer above for a detailed description.
NOTE: Your lab instructor will tell you what will be marked for this lab.

1. C String Manipulation functions

By now, you have learned how to declare a char variable to hold characters.  You might also have learned that a string (like a person's first or last name") in C++ can simply be represented by a null-terminated sequence of characters stored in a char array. These days you can use the string type for strings. In the bad old days, before circa 1994, you had to use character arrays, because there was no native string type in C++ most implementations. There is still no string type in C. A string, represented as a character array, is called a "C string".

Here's a quick little review of declaring and initializing C strings.



	To declare a character array:   
	
			 char s1[8]; 


	To assign a value to an array when you declare it:
	
			 char s1[8] = "one"; 

	Actually, if you are assigning a value at the same time as
	you are declaring the char array, you don't
	need to specify an array size.
	
			 char s1[] = "one"; 

	Assigning a value either way results in a character array
	of finite length, established at compile time.
	

Note: You cannot assign the value of a C string after the declaration
as you do with other simple variable assignments.
i.e. s1 = "one";    <- WRONG

To assign a value after the declaration, you need to use
a C String function such as strcpy. We'll look at that next.

There are two different ways to refer to an array when its size is not important. You can write char arr[] or you can write char *arr. You will need to know both methods to understand the following discussion. The first way is what you were taught in CS 110. The second can be used in declarations and in function headers and prototypes – wherever you would see char arr[]. They are equivalent. You use the same syntax to refer to an element of both types of array. They are passed to functions the same way too.

C++ supports a wide range of C string manipulation functions. Following are some of them:

    1.1 strcpy

      Use this function if you would like to copy one string to another string.  The syntax of this function is
 strcpy(char *s1, const char *s2) where s1 is the copy and s2 is the original.  Following is an example:

// File name: ~ftp/pub/class/170/ftp/cpp/StringClass/Copy1.cpp
// Purpose:   Demonstrates the use of strcpy()

#include <cstring>
#include <iostream>
using namespace std;
#define COPY_SIZE 64   // maximum characters to copy
int main()
{
	const char *Original = "I am the original!";
        char Copy[COPY_SIZE + 1] = "I am the copy!";

	cout << "Before strcpy(): " << endl;
	cout << "Original = " << Original << endl;
	cout << "Copy = " << Copy << endl;

	strcpy(Copy, Original);
	cout << "After strcpy(): " << endl;
	cout << "Original = " << Original << endl;
	cout << "Copy = " << Copy << endl;

	return 0;

}

    Here is the running result of the above program:

mercury[156]% CC -o Copy1 Copy1.cpp 
mercury[157]% Copy1
Before strcpy(): 
Original = I am the original!
Copy = I am the copy!
After strcpy(): 
Original = I am the original!
Copy = I am the original!
mercury[158]% 


    1.2 strlen

        Use this function if you would like to know the length of a string.  The syntax of  this function is strlen(const *char str). Following is a simple program demonstrating the use of strlen:

// File name: ~ftp/pub/class/170/ftp/cpp/StringClass/StrLen.cpp
// Purpose:   Demonstrates the use of strlen()

#include <cstring>
#include <iostream>
using namespace std;

int main()
{
	const char *String= "I am the string!";

	cout << "Here is string:" << String << endl;
	cout << "Its length is: " << strlen(String) << " characters\n";

	return 0;

}

Here is the running result of the above program:

mercury[166]% CC -o StrLen StrLen.cpp 
mercury[167]% StrLen
Here is string:I am the string!
Its length is: 16 characters
mercury[168]% 

    

    1.3 strncpy

strncpy is a variation of strcpy. It's syntax is: strncpy(char *s1, const char *s2, size_t n), where size_t is simply unsigned int. It simply copys n characters from s2 to s1. Following is an example:

// File name: ~ftp/pub/class/170/ftp/cpp/StringClass/Copy2.cpp
// Purpose:   Demonstrates the use of strncpy()

#include <cstring>
#include <iostream>
using namespace std;

#define COPY_SIZE 64 
int main()
{
	const char *Original = "I am the original!";
	      char Copy[COPY_SIZE + 1] = "I am the copy!";

	cout << "Before strncpy(): " << endl;
	cout << "Original = " << Original << endl;
	cout << "Copy = " << Copy << endl;

	// calls strncpy and strlen
	strncpy(Copy, Original, COPY_SIZE); 
	Copy[COPY_SIZE + 1] = '\0';

	cout << "After strncpy(): " << endl;
	cout << "Original = " << Original << endl;
	cout << "Copy = " << Copy << endl;

	return 0;

}

Running result:

mercury[187]% CC -o Copy2 Copy2.cpp 
mercury[188]% Copy2
Before strncpy(): 
Original = I am the original!
Copy = I am the copy!
After strncpy(): 
Original = I am the original!
Copy = I am the original!

For more string manipulating functions, refer to your text book or type  man strcpy at your Unix command prompt.

2. STL String Class

    C String is one of the two ways that you can manipulate strings in C++.  The other way is through the STL string class library. This allows strings to be represented as objects in C++. The STL string class gives you strings of unbounded length because the string space is allocated at run-time. Compare this to C Strings where the finite string length of char array variables is defined at compile time.

Moreover, assignment, comparison, and concatenation of strings using the STL class is arguably easier than using C Strings. However, you'll still see C String code around in older programs so it's best to know both.

STL stands for "Standard Template Library". The Standard Template Library is a new C++ library that provides a set of easily composable C++ container classes and generic algorithms (template functions). For the time being, you don't have to worry too much about STL.  It is enough for you to keep in mind that  one of the classes provided by STL is the string class.  

    Why, you may ask, do we need STL string when we already have C string?  Here is why: null terminated strings (C strings) cannot be manipulated by any of the standard C++ operators.  Nor can they take part in normal C++ expressions.  For example, consider this fragment:

char s1[80], s2[80], s3[80];

s1 = "one";   // error
s2 = "two";   // error
s3 = "three"; //error

    As the comments show, in C++, it not possible to use the assignment operator to give a character array a new value.  To do this, you need to use the strcpy function that was discussed above:

strcpy(s1, "one");
strcpy(s2, "two");
strcpy(s3, "three");

    There are also other reasons for including string  in the STL.  For example, the null-terminated character arrays does not check if the array is out of bound and that contributes to many string problems encountered by C++ programmers, experienced and inexperienced alike.

    Following is an example showing you how to use the STL string class to manipulate strings.  The example gives you a feeling of  how the STL string works, which means you do not need to remember how it really works. 

// File name: ~ftp/pub/class/170/ftp/cpp/StringClass/StlString.cpp
// Purpose:   Demonstrates the use of STL string
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string str1("This is a test");
	string str2("ABCDEFG");
	
	cout << "Initial strings: \n";
	cout << "str1: " << str1 << endl;
	cout << "str2: " << str2 << "\n\n";
	

	// demonstrate length()
	cout << "Length of str1 is: " << str1.length() << endl;

	// demonstrate insert()
	cout << "Insert str2 into str1:\n";
	// insert str2 to str1 starting from the 5th position
	str1.insert(5, str2);
	cout << str1 << "\n\n";
	
	// demonstrate erase()
	cout << "Remove 7 characters from str1: \n";
	// remove 7 characters from str1 starting from the 5th position
	str1.erase(5, 7);
	cout << str1<< "\n\n";
	
	// demonstrate replace
	cout << "Replace 2 characters in str1 with str2:\n";
	// starting from the 5th position of str1, replace 2 characters of
	// str1, with str2
	str1.replace(5, 2, str2);
	cout << str1 << endl;
	
	return 0;
}	

    Here is how it runs:

mercury[36]% CC -o StlString StlString.cpp 
mercury[37]% StlString
Initial strings: 
str1: This is a test
str2: ABCDEFG

Length of str1 is: 14

Insert str2 into str1:
This ABCDEFGis a test

Remove 7 characters from str1: 
This is a test

Replace 2 characters in str1 with str2:
This ABCDEFG a test
mercury[38]% 

3. Summary and References for C strings and C++ strings

The following table shows some C-string functions and STL functions. A few of these have been illustrated in detail in this web page, others are just included for your reference.

C-String Functions
strcpy(str1, str2) Copies str2 to str1.
strlen(str) Returns the number of characters in str.
strcat(str1, str2) Concatonates (joins) str2 to str1.
strcmp(str1, str2) Compares str1 to str2.
If str1 == str2 return 0.
If str1 < str2 return -1. e.g. strcmp("a",b")
If str1 > str2 return +1. e.g. strcmp("b",a")
STL Class Functions
str.length() Returns the number of characters in str.
str1.insert(pos, str2) Insert str2 into str1 starting at pos.
str1.erase(pos, n) Delete n characters in str1 starting at pos.
str1.replace(pos, n, char) Replace n characters in str1 with char x starting at pos.
str1.append(str2) Appends str2 to str1.
str1.compare(str2) Compares str1 to str2.
If str1 == str2 return 0.
If str1 < str2 return -1. e.g. strcmp("a",b")
If str1 > str2 return +1. e.g. strcmp("b",a")
str1.substr(pos, n) Return n characters in str1 starting at pos.
str1.swap(str2) Exchange contents of str1 and str2.
(A useful function in programs that sort strings.)

Lab Exercise:


This page last modified:
Tuesday, 09-Oct-2007 00:47:08 CST

CS Dept Home Page
CS Dept Class Files
CS115 Lab Files

Copyright: Department of Computer Science, University of Regina.