Manipulating String Data in C++, Assignments of Electrical and Electronics Engineering

How to create and manipulate character string data in c++ using both cstrings and the c++ string class. It covers declaring and initializing string variables, concatenation, input/output, and converting between string objects and cstrings. It also introduces the vector class.

Typology: Assignments

Pre 2010

Uploaded on 09/17/2009

koofers-user-7bq
koofers-user-7bq 🇺🇸

10 documents

1 / 38

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Strings
Read: Chapter 8.
Q: How can we create and manipulate variables
holding character string data?
Two Ways:
Using “cstrings”, supported by both C and C++.
Using C++ string class.
cstrings in C++:
A cstring is simply a partially-filled array
having base type char and with a null character
‘\0’ to mark the end of the character string stored
in the array.
They are arrays first and “strings” second!
A cstring variable is declared in exactly the same
way as an array of characters but will be used
differently.
Syntax in Declaring a cstring Variable:
char array_name[max_cstringSize + 1];
This declaration will create a cstring variable (an
array of char) that is capable of storing a string with
at most max_cstringSize characters.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26

Partial preview of the text

Download Manipulating String Data in C++ and more Assignments Electrical and Electronics Engineering in PDF only on Docsity!

Strings

Read: Chapter 8.

Q: How can we create and manipulate variables holding character string data?

Two Ways:

  • Using “ cstrings ”, supported by both C and C++.
  • Using C++ string class.

cstrings in C++:

  • A cstring is simply a partially-filled array having base type char and with a null character ‘\0’ to mark the end of the character string stored in the array.
  • They are arrays first and “strings” second!
  • A cstring variable is declared in exactly the same way as an array of characters but will be used differently.

Syntax in Declaring a cstring Variable: char array_name[max_cstringSize + 1];

This declaration will create a cstring variable (an array of char) that is capable of storing a string with at most max_cstringSize characters.

Initializing cstring Variable during Declaration: Consider char s[10] = “Hi Mom!”;

The array elements are:

s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9] H i M o M! \0??

Remarks:

  • The character ‘\0’ is a null character used as a sentinel value to mark the end of a cstring stored in an array.
  • The cstring variable s has length 8.
  • Warning: The following are illegal in C++. char s[10]; s = “Hi Mom!”;

Q: What if the max_cstringSize is not specified?

Example: char q[] = “jrm” // q has 4 characters

The array elements are: q[0] q[1] q[2] q[3] *j r m *

Example: The following loop will change a cstring, our_string, into a cstring having the same length but with characters all ‘X’:

int index = 0; while (our_string[index] != '\0') { our_string[index] = 'X'; index++; }

Remark: In the loop above, if our_string has no null terminator, the loop will run off into memory, happily writing on every byte in memory beyond the end of our_string until a byte is found with zero value.

Better using: int index = 0; while (our_string[index] != '\0' && index < size) { our_string[index] = 'X'; index++; }

Assignment Operator in cstring: Warning: The assignment operator does not work for cstrings. Hence, the following are illegal in C++. char s[10]; s = “Hi Mom!”;

However, during declaration, it is legal to use: char s[10] = “Hi Mom!”;

To assign a value to a csting variable, use strcopy function defined in the cstring library.

Example: #include … char s[10]; strcpy(s, “Hi Mom!”);

Warning: In C++, strcpy function does not check the declared length of the first argument. Hence, it is possible for strcpy to write characters beyond the declared size of the array!

Remedy: Many versions of C++ have a safer version of strcpy named strncpy, which includes a third argument representing the maximum number of characters to copy.

Comparing cstrings: The “==” comparison operator does not work as expected with cstrings. To compare two cstring variables, use the predefined function strcmp defined in the cstring library.

Example: #include … if (strcmp(c_string1, c_string2)) cout << “Strings are not the same.”; else cout << “String are the same.”;

Remark: The strcmp function compares the numeric codes of the elements in the C-strings one character at a time.

  • If the two cstrings are the same, strcmp returns 0, which will be interpreted as false.
  • As soon as the characters do not match, strcmp returns a negative (positive) value if the numeric code in the first parameter is less (greater) than the numeric code in the second parameter, which will be interpreted as true.

Example: The following are either disallowed or they don’t do what you would expect: void doThings( ) { char myString[5]; myString = “abc”; char stringA[] = “Hello”; char stringB[] = stringA; if (stringB == “Hello”) cout << “Hello\n”; }

Correct Way: #include void doThings( ) { char myString[5]; strcpy(myString, “abc”); char stringA[] = “Hello”; char stringB[6]; strcpy(stringB, stringA); if (!strcmp(stringA, stringB)) cout << “Hello\n”; }

Passing cstrings as Arguments and Parameters: Since cstring variables are arrays, cstring arguments and parameters are used just like array variables.

Example: Replace all vowels in a string with an underscore character. void replaceVowels(char str[ ]) // we don’t pass a length { int i = 0; while (str[i] != ‘\0’) { switch (str[i]) { case ‘a’: case ‘e’: case ‘i’: case ‘o’: case ‘u’: case ‘A’: case ‘E’: case ‘I’: case ‘O’: case ‘U’: str[i] = ‘_’; break; }

i++; } }

void tryIt( ) { char command[ ] = “Let’s eat apples”; replaceVowels(command); cout << command << endl; }

Remarks:

  • If a function changes the value of a cstring parameter, it is best to include a parameter for the declared size of the cstring.
  • If a function does not change the value of a cstring parameter, the null character can detect the end of the string and no size argument is needed.

Consider the code: char a[80], b[80]; cin >> a >> b ; cout << a << b << “END OF OUTPUT\n”;

Dialogue: Do be do // input DobeEND OF OUTPUT // output

Q: How can we read in an entire line?

Remarks:

  • To get an entire line, you can write a loop to extract the line one character at a time, but this won’t read the blanks.
  • To read in blanks, use the member function get.
  • To get an entire line, you can also use the predefined member function getline (of every input stream).
  • getline has two arguments: The first argument is a cstring variable for receiving the input, and a second argument is an integer specifying the number of characters to be extracted to the cstring, allowing for the null terminator.

The getline Function: Syntax: input_stream.getline(cString, max_char + 1);

One line of input is read and stored in the cstring cString. The getline member function will stop reading when max_char characters have been read.

Example: char a[80]; cin.getline(a, 80); cout << a << “END OF OUTPUT.\n”;

Dialogue: Do be do // input Do be doEND OF OUTPUT // output

Remark: These cstring I/O techniques work the same for file I/O streams.

  • Replace cin (cout) with the name of an input (ouput) file stream, we may use: in_stream >> c_string; in_stream.getline(c_string, 80); out_stream << c_string;
  • The function atoi takes a cstring of digits and returns the int value represented by the digit characters in cstring. It returns 0 if the cstring contains a non-digit character. Example: atoi(“168”) returns 168. atoi(“#168”) returns 0.
  • The function atol is similar to atoi except it converts its cstring argument to the long value the cstring represents.
  • The function atof converts its cstring argument to the double value the cstring represents. Like atoi, the function atof returns 0.0 if the cstring argument does not represent to a double. Example: double x = atof(“1.68”); // x = 1. double x = atof(“$1.68”); // x = 0.

Q: How do we read the input?

Consider the following function read_and_clean ,

  • It reads a line of input.
  • Discards all characters except the digits '0' through '9'.
  • Uses atoi to convert the "cleaned-up" cstring to int.

Array of cstrings:

  • A cstring is an array of base type char.
  • An array of cstrings can be considered as a two- dimensional array with base type char.
  • Like any array, an array of cstrings can be manipulated by using its index values.

Example: char name[5][20]; // define 5 cstrings of size 19 cout << “Enter 5 names, one per line:\n “; for (int index = 0; index < 5; index++) cin.getline(name[index], 20); for (int index = 0; index < 5; index++) cout << name[index] << endl;

Example: Passing Array of Cstring as Parameter. // Define 10 cstrings, each can hold up to 49 characters char stringArray[10][50]; for (int i=0 ; i<10 ; i++) cin >> stringArray[i]; // read in the string … void lookForBoo(char words[][50], int nWords) { for (int i=0 ; i<nWords ; i++) if (strcmp(words[i], “Boo”) == 0) // Finding “Boo”. cout << “You scared me!\n”; }

Manipulating Character Strings:

  • Using cstring.
  • Using string class

Problems with Cstrings:

  • Does not behave like a simple data type; standard operators do not apply. Example: Assignment and compare operators do not work on cstrings.
  • Using cstrings with predefined cstring functions is not as safe as we would like. Example : Using strcpy to copy a longer cstring to another (shorter) cstring will overwrite memory that may be important to your program.

C++ string Class:

  • Developed as a safer and easier way to manipulate character strings.
  • Class strings behave very much like built-in data types.
  • Have extensive utility in the Standard Library.

Using Standard String Class in C++: Include Directive: #include using namespace std;