C++ Strings / PDF

C++ Strings / PDF




C++ Strings / PDF






Sample of the pdf document 









C++ String Variables

The standard C++ library provides an object string type to complement the string
literals used earlier:

string Name1, // must #include
Name2;
A string variable may be assigned the value of a string literal or another string variable:

Name1 = “Bjarne Stroustrup”;
Name2 = Name1;
string myString;
myString = ‘N’;
const int asciiN =78;
myString = asciiN; // string equals “N”


String Initialization

A string variable may be initialized at the point of declaration:
string Greet1 = “Hello”,
Greet2 = Greet1;

It is not, however, legal to assign a char or int value to a string in the declaration:

string String1 = ‘N’, // illegal
String2 = 78; // illegal
Since it would be legal to assign ‘N’ to String1, you might ask why it is illegal
to initialize String1 with ‘N’ in the declaration of String1. The full reason would take us into a discussion of the notion of a class in C++, a topic not covered in this course.

Suffice it to say at this point that the statements above are true.


It is not legal to have a line break within a string literal in C++:

string BadString = “It is as a tale told by an idiot, // not
full of sound and fury, // legal
signifying nothing.”;
. . . however, somewhat perversely, this is OK:

string LongString = “It is as a tale told by an idiot, ”
“full of sound and fury, ”
“signifying nothing.”;
And, of course, it is legal for a string literal to contain a newline character:

string Prompt = “Type your user id below and press :\n”;



String Output


A string variable may be printed by inserting it to an output stream, just as with any simple variable:

string Greetings = “Hello, world!”;
cout << Greetings << endl;

Just as with string literals, no whitespace padding is provided automatically, so:

cout << Greetings << “It’s a wonderful day!”;
would print:
Hello, world!It’s a wonderful day!
Of course, you can provide whitespace yourself:
cout << Greetings << “ ” << “It’s a wonderful day!”;..............








 Click here for  Download PDF / FREE


C++ Strings / PDF



0 commentaires: