Programming in C: Unit II (b): Strings

Strings Taxonomy

Programming in C

Fixed-length string When storing a string in a fixed- length format, you need to specify an appropriate size for the string variable. If the size is too small, then you will not be able to store all the elements in the string.

STRING TAXONOMY

In C, we can store a string either in fixed-length format or in variable-length format as shown in Figure 6.4.

Fixed-length string When storing a string in a fixed- length format, you need to specify an appropriate size for the string variable. If the size is too small, then you will not be able to store all the elements in the string. On the other hand, if the string size is large, then unnecessarily memory space will be wasted.

Variable-length string A better option is to use a variable length format in which the string can be expanded or contracted to accommodate the elements in it. For example, if you declare a string variable to store the name of a student. If a student has a long name of say 20 characters, then the string can be expanded to accommodate 20 characters. On the other hand, a student name has only 5 characters, then the string variable can be contracted to store only 5 characters. However, to use a variable-length string format you need a technique to indicate the end of elements that are a part of the string. This can be done either by using length-controlled string or a delimiter.

Length-controlled string In a length-controlled string, you need to specify the number of characters in the string. This count is used by string manipulation functions to determine the actual length of the string variable.

Delimited string In this format, the string is ended with a delimiter. The delimiter is then used to identify the end of the string. For example, in English language every sentence is ended with a full-stop (.). Similarly, in C we can use any character such as comma, semicolon, colon, dash, null character, etc. as the delimiter of a string. However, null character is the most commonly used string delimiter in the C language.

You must be having some confusion when we use the term string and character array. Basically a string is stored in an array of characters. If we are using the null character as the string delimiting character then we treat the part of the array from the beginning to the null character as the string and ignore the rest. Figure 6.5 illustrates this concept.

Note

In C, a string is a variable length array of characters that is delimited by the null character.

Programming in C: Unit II (b): Strings : Tag: : Programming in C - Strings Taxonomy