Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use

Strings

String Literals

A string literal is any alphanumeric enclosed in double quotation marks.  All string literals end with a string-terminating zero (NULL).  Visual C++ uses this string-terminating zero to determine the end of a string value.

Notice how the string literal "Dogs Rule!" would be represented:

D o g s   R u l e ! \0


Warning!  String literals that contain only numbers are NOT to be thought of as "true" numbers.  They are simply strings of digits that cannot be used to perform mathematical calculations such as addition or multiplication.  Calculations can be performed only on numeric data -- never on string literals.

 

 

String Lengths

The length of a string is the number of characters up to but not including the null zero.
String Length
"R" 1
"5" 1
"Wally"  5
"" 0
"My Computer" 11


Character literals ALWAYS have a length of one.  There is no null zero terminator for character literals. 

The letter 'R' as a character in memory:  
R
The letter "R" as a string in memory:
R \0

 


Storing Strings in Arrays

There are NO string variable types in the Standard C++ language.  Instead, strings are stored in character arrays.

Think of an array as a big "box" subdivided into compartments.  Each compartment in the array will hold the same type of variable.  You may have worked with arrays (vectors/matrices) in mathematics.  A character array can hold one or more character variables in a row in memory.

char dogName[10];      //dogName holds a string

dogName is the name of this array of characters.  Brackets ( [ ] ) are always included after an array name to indicate the presence of the array and specify its array length.  This array is 10 characters long.  Character arrays may be filled at the time of declaration.

char dogName[10] = "Wally Dog";

W a l l y   D o g \0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]


NOTE:  The elements of the array are subscripted, starting with the number zero.

NOTE:  Be sure to make the array size large enough to hold the string AND its null-terminating character (\0).   (There are 10 boxes needed to hold "Wally Dog".) 

NOTE:  Never try to assign string values to character arrays using a regular assignment statement, except when you first declare the character array.

dogName[10] = "Wally Dog";   //WON'T WORK!!!!!!!!!!!

 

Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use