-->

Introduction to Strings

Introduction to Strings
Strings
An array is a data structure that contain a collection of data objects of the same data type. 
A string is an array of characters terminated by the NULL character. It is a sequence of characters treated as a group. 
C program uses delimited strings. 
Some example strings: 
  • "filename" 
  • "output string" 
A data object is a region of storage that contains a value or group of values. Each value can be accessed using its identifier. Each object has a unique data type. The data type of an object determines the storage allocation for that object.

Examples: integer, floating-point, character, Booleans, void, pointers, arrays, structures, unions, enumerations
Storing Strings and Characters
A String containing a single character takes up to 2 bytes of storage.
Note: A string literal is enclosed in double quotes

Differences between Strings and Character Arrays 
The difference between string and character array is, the string character ends with the null character. 

The character string has an array size of eleven. Hence, the string ends after 'y'. The remaining two columns are not a part of the array.

Character Literals and String Literals 

A string literal is a sequence of characters enclosed in double quotes. It is also known as a string constant. A character literal is a sequence of characters enclosed in single quotes. 
For example, the character string: 
char s1 ="a"; //Takes two bytes of storage. 
s1:
a
\0
On the other hand, the character, in single quotes: 
char s2= 'a' ; //Takes only one byte of storage. 
s2:
a

String Literal References 
String literal reference is the representation of a string value within the source code of a computer program. It is a sequence of characters enclosed in double quotes. 
From the above program it is clear that when the array subscript in the printf is taken as '1', then the value 'e' is printed.

Declaring Strings 
The array size of string is 9, the array looks as given on right side. 
The string pointer is declared as a character. In order to display the array, the string 'pStr' should be initialized. 
Hence, the memory location of the string must be allocated before the string can be used.

Initializing Strings 
To initialize a C string during declaration: 
    char my_message [20] = "Good Day" 
The null character '\O' is added, at the end. 
Another alternative: 
    char short_string [] = "Good Day"

Related Posts

Subscribe Our Newsletter