CS115 Lab: C++ Strings


Highlights of this lab:

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.

Debugging C++ with gdb

There are two kinds of errors that you will encounter as you develop projects in C++. The problem of how to resolve the logic error remains. You could guess where in your program the error occurred and put in some cout statements there to print out the value of variables to see what was happening. Sometimes this works but then you're left with having to delete all the cout statements and hope that you don't accidentally take out some good code while you're doing it.

A better solution is to use a debugger program so that you can control how your program is running. Here are some of the basic actions you want to perform:

Running the gdb Debugger

Before you can use gdb on a program, you must prepare your program for debugging with gdb. You must compile it with the -g or -ggdb option. The -g option creates additional information about the program and deposits it in a symbol table. (The -ggdb option creates more information of this type.) The debugger must have this symbol table to do its work. The general syntax is:
        g++ -g filename.cpp -o executable_file
Start gdb by typing in the following command:
        gdb executable_file
where executable_file is the executable version of the program. Remember: if you do not use the -o option when you compile a program, the executable file will be called a.out.

The system prompt changes to the gdb prompt, and you are ready to start entering gdb commands. There are many commands available but the following table shows some of the basic ones.

GDB Command Summary

Command Action
help Display information about gdb commands.
run Start running the program under gdb.
print expression Display the contents of a variable or expression.
break function Set a breakpoint at the designated function.
clear function Clear the breakpoint set at the designated function.
delete [number] Delete all breakpoints if no number is specified, or deletes just the breakpoint specified by number.
info breakpoints Display the number of each breakpoint.
step Execute just the next line of code.
next Execute just the next line of code but skip over any function calls in the line.
list Display lines of source code.
quit Exit gdb.

As is the case with most debuggers, the best way to learn gdb is to actually use it on a program. There is an simple program you can use to do this in the lab exercise. Here is a list of the references for using gdb:

On Hercules Use dbx

If you would like to learn the debugger on Hercules, please click here

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.String Class

    C String is one of the two ways that you can manipulate strings in C++.  The other way is through the string class. This allows strings to be represented as objects in C++. The 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 string 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.

    Why, you may ask, do we need the string class 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 using strings  .  For example, the null-terminated C String 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 string class to manipulate strings.  The example gives you a feeling of  how string objects work, 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 the string class
#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 string 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")
String 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, 11-Oct-2011 13:48:24 CST

CS Dept Home Page
CS Dept Class Files
CS115 Lab Files

Copyright: Department of Computer Science, University of Regina.