Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1.Let\'s discuss how C-style strings are used in a program. How do you create a

ID: 3554609 • Letter: 1

Question

1.Let's discuss how C-style strings are used in a program.
How do you create a C-style string? Give examples.

2.You have been using the string type throughout this course.
What new features have you discovered about the string type this week?
Give some examples of how you might be able to use these new string capabilities in a program.

The string type is generally more flexible than the C string type. The string type can be used with many of the C++ operators. One string variable can be assigned to another using the assignment operator. Two string variables can be compared using the relational operators. Two string variables can be concatenated to form a new string using the "+" operator.

In addition to these conveniences, there are many functions supplied with the string type to operate on string variables. You can find a complete listing of operators and functions that are part of the string type by doing an Internet search on "C++ string type."

One significant difference between the string type and C strings is that string variables are not constrained to their initial size! This can be seen simply by using the push_back(someChar) function, which is used to add characters to the end of a string variable.

string str;
str.push_back('X');   // Add the character 'X' to the end of the str variable

While a large character array can be declared to hold any C string up to its size limit, a string variable effectively has no limit. This is accomplished using dynamic memory allocation, which you will be studying in your next programming class!

As was mentioned earlier, there are many functions that require a C string as a parameter. If you are using string variables, there is an easy way to extract a C string from a string variable. The c_str( ) function returns a C string containing the characters from the string variable.

string str = "Hello There";
str.c_str();                 // Returns a C string containing "Hello There".

Explanation / Answer

1. C-style string can be created by creating an array of characters. example:
char cArray[10];
It will create a C-style string of maximum size 10
To print the whole C-string cArray, use:
cout << cArray;
To print a character at a particular position, we can do this:
cout << cArray[2];
This will print the character stored at index 2 of the C-string cArray.


2. string type is easier to use. Although the elements of a string type variable can be accessed in the similar manner as that of C-strings, the string types are flexible(they don't have a size limit). They can be concatenated using + operator