{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

6.StringsFileIO

6.StringsFileIO - Strings Astring InC, char...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
Strings y A string is composed of a sequence of characters y In C++, a string can be represented using an array of char A h t t h t th it t t l l th y character array can store any sequence shorter than its total length y A special character called the null character , written as ‘ \0 ’, is used to signal the end of the sequence y Hence a character array of size n can only store a string with n 1 characters y Examples: char msg1[80] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}; char msg2[80] = “Hello”; C ll h t t b H e l l o \0 0 1 2 3 4 5 6 7 8 75 76 78 79 1 char msg2[80] = Hello ; C++ allows a character array to be initialized using a string literal which is in fact a null terminated sequence of characters
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Simpler way to handle strings: String Class y As strings are frequently used in programs, C++ provides a class string (like data type) for easy string manipulations y To use the class string simply include the header file string , simply include the header file using the include directive , i.e., y A string object (like variable) can be declared using the class #include <string> name string , and initialized with any null terminated sequence as follows: char a[] = “Hello”; // initialized using an equal sign string msg1 = a; char a[] = “Hello”; // initialized using its constructors string msg1(a); 2 string msg2 = “World”; string msg3 = msg1; string msg2(“World”); string msg3(msg1);
Background image of page 2
Assignment Statement y A string object may also be initialized or changed at a later time after its declaration using an assignment statement y An assignment statement consists of a string object on the left hand side of an equal sign , and a null terminated sequence or an expression that returns a string object on the right hand side y Examples: char a[] = “Hello”; char a[] = Hello ; string msg1, msg2, msg3; msg1 = a; msg2 = “World”; 3 msg2 = World ; msg3 = msg1;
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
String Concatenation y Two strings can be concatenated to form a longer string using the binary operator + y Examples: string msg1 = “I love ”; string msg2 = “cats”; string msg3 = msg1 + msg2; “I love cats” “I love dogs” y Note that at least one of the operands must be a string object string msg4 = msg1 + “dogs”; string msg5 = “I hate ” + msg2; “I hate cats” in using the binary operator + y The following expression is therefore invalid 8 4 string msg = “I love ” + “lions”;
Background image of page 4