You are on page 1of 32

STRINGS

(ARRAY OF CHARACTERS)
Lecture Notes Prepared by
Melody Angelique C. Rivera
Faculty, College of Computer Studies, Silliman University
(Reference: Foundations of C Programming by Forouzan and Gilberg
Strings
• A series of characters treated as a unit
• Some programming languages like Pascal, Ada and C++ have intrinsic string
types
• C does not have a primitive data type (e.g., int) for a string
• A C programmer implements a string as an array of characters
• All string implementations treat a string as a variable-length piece of data
(e.g., a name)
String Taxonomy

String

Fixed- Variable-
length length
C strings

Length-
Delimited
controlled
Fixed-length Strings
• You need to decide on the size of the string variable (array of characters)
• Problems:
• If it is too small, the data might not fit
• If it is too large, memory will be wasted
• How to determine data from non-data
• Common solution: add non-data characters at the end of the data (such as spaces)
• Downside: You cannot use the selected non-data character as data anymore
Variable-length Strings
• A structure that can expand and contract to accommodate the data
• Problem: how to tell when the data ends
• Two common techniques:
• Length-controlled strings
• Add a count that specifies the number of characters in the string
• This count is used by the string manipulation functions to determine the actual length
of the data
• Delimited strings
• Uses a delimiter to identify the end of the string (\0 – the ASCII null character)
• (just like a period ends a sentence, which is variable-length string)
• Disadvantage: uses a space that could have been used to store data
STRINGS IN C
C Strings
• A sequence of characters of variable-length delimited by (or ending with)
the null character, a special character represented by \0
• In general, string characters are selected only from the printable character
set
• But C does not prevent any character (aside from the null character) to be
used in a string
• Therefore, formatting characters like tabs can be used in a string
Storing Strings
• Strings are stored in an array of characters and terminated with \0
• The name of the string is a pointer to the beginning of the string

A character; requires only 1 memory location A string with 1 character; requires 2 memory locations
H H \0

An array of characters An empty string


H e l l o ! \0

A string with 6 characters


H e l l o ! \0
The String Delimiter
-why we need a null character at the end of a string
• Because a string is not a data type but a data structure
• Its implementation is logical, not physical
• The physical structure is the array in which the string is stored
• Since the string is a variable-length structure, identifying the logical end of
the data within the physical structure is necessary
• The null character is used as an end-of-string marker (the sentinel used by
the standard string functions)
• A sentinel is a special or dummy value that uses its presence as a condition
of termination
String Literals
• Also known as a string constant
• A sequence of characters enclosed in double quotes
• Examples:
"C is a programming language."
"Hello, World! “
• C automatically (1) creates an array of characters, (2) initializes it to a null-
delimited string, and (3) stores it while remembering its address
• It does all these processes because the double quotes is used to immediately identify
the data as a string value
Comparing Strings and Characters (1)
Character literal String literal
• Enclose in single quotes • Enclose in double quotes
• Example: 'a’ • Examples: "a" (a string with 1
character), " " (an empty string)
• Occupies only a single memory
location • Needs an extra memory location to
store the delimiter (\0)
• Moving a characters from one
memory location to another only • Moving strings requires a call to a
requires an assignment operator (=) string function
letter = 'a'; • You cannot use the assignment
operator (=)
Comparing Strings and Characters (2)
-representing the absence of data

Character literal String literal


• Technically, there is no such thing as • A string can be empty
an empty character
• Since it is a variable-length structure,
• Logically, a space (' ') or a null a string can exist with no data in it
character ('\0') is used
• A string with no data consists of only
• Since the space and null character are the delimiter (\0)
characters, both these specifications
require that we program for the • This concept is specified in the
interpretation of no data definition of the string and is
programmed into all the string-
handling functions
Referencing String Literals
• Since a string literal is stored in memory, it has an address
• You can refer to it using pointers

• A string literal is an array of characters and is itself a pointer constant to the


first element of the string
• When you use the string literal, you are referring to the entire string

• It is also possible to refer to only one character in the string


Declaring Strings
• In defining the array to store a string, you must provide enough room for
the data and the delimiter
• The storage structure must be one byte larger than the maximum data size
• Syntax: char <var-name>[<size>];
• For example: declaring an 8-character string, including its delimiter
char str[9];
Initializing Strings (1)
• Assign a value to the string when it is defined
char name[10] = "Juan";

• this example uses a literal string (a sequence of characters enclosed in double quotes)
• the compiler automatically adds the terminating null character at the end of the string
Initializing Strings (2)
• As an array of characters
char name[10] = {‘J’, ‘u’, ‘a’, ‘n’, ‘\0’};

• Tedious to code
• Must ensure that there is a null character at the end of the string
Initializing Strings (3)
• Without indicating the size of the array
char name[] = "Dumaguete City";

• if you do not specify the number of subscripts when you declared the array, the compiler
calculates the size of the array for you
• the example above will declare a 15-element array (the null character is stored in the 15th
memory location)
String Input Functions (1)
scanf()
• Conversion code: s
• Skips the rest of the string once it encounters a space (e.g., “Hello there!”)
• only “Hello” will be stored
• Example 1:
char month[10];

scanf(“%s”, month); //no need for & because month is already
//a pointer constant
• Example 2:
scanf(“%9s”, month); //protecting against the user entering too
//much data
String Input Functions (2)
gets()
• No need for conversion code
• Reads all characters typed at the keyboard up to the first newline character
(which you generate by pressing the Enter key)
• Example:
char month[10];

gets(month);
String Output Functions (1)
printf()
• Conversion code: s
• Example:
char string1[10] = "Dumaguete";

printf(“%s”, string1);
String Output Functions (2)
puts()
• No need for conversion code
• Example:
char string1[10] = "Dumaguete";

puts(string1);
Sample Program
See sample program in the Virtual Classroom under the String Functions
section
BASIC STRING
HANDLING FUNCTIONS
IN C
Found in <string.h> header file
strcat
(string concatenation)
• Concatenates or joins the strings s1 • Example:
and s2
char str1[15] = “Hello, ”;
• A copy of s2 is appended to the end char str2[7] = “World!”;
of s1 strcat(str1, str2);
printf(“%s”, str1);
• The programmer must ensure that s1
points to enough space to hold the
result • Output: Hello, World!
• The string s1 is returned (the
destination)
• Syntax: strcat(<s1>, <s2>);
strcpy
(string copy)
• Copies the string s2 into the string s1, • Example:
including the terminating null
character char str1[15] = “Hello, ”;
char str2[7] = “World!”;
• Whatever exists in s1 is overwritten printf(“%s\n”, str1);
strcpy(str1, str2);
• The programmer must ensure that s1 printf(“%s”, str1);
points to enough space to hold the
result
• Output: Hello,
• The value s1 is returned World!
• Syntax: strcpy(<s1>, <s2>);
strcmp
(string compare – case-sensitive)
• The strings are compared character • Example:
by character starting at the
characters pointed at by the two char str1[15] = “Hello”;
pointers char str2[7] = “hello”;
int result;
• if the strings are identical, the integer result = strcmp(str1, str2);
value zero (0) is returned if (result == 0)
printf(“The strings are equal.”);
• As soon as a difference is found, the else
comparison is halted and if the ASCII printf(“The strings are not equal.”);
value at the point of difference in the
first string is less than that in the
second (e.g., 'a' 0x61 vs. 'e' 0x65) a • Output: The strings are not equal.
negative value is returned; otherwise,
a positive value is returned
• Syntax: strcmp(<s1>, <s2>)
stricmp
(string compare – ignore the case)
• Compares s1 to s2, ignoring case • Example:
• Returns a value that is lesser than char str1[15] = “Hello”;
0 if s1 is less than s2, equal to 0 if s1 is char str2[7] = “hello”;
the same as s2, greater than 0 if s1 is int result;
greater than s2
result = stricmp(str1, str2);
• The same as the macro strcmpi() if (result == 0)
printf(“The strings are equal.”);
• Syntax: stricmp(<s1>, <s2>) else
printf(“The strings are not equal.”);

• Output: The strings are equal.


strlen
(string length)
• Returns the length of the string s • Example:
• The length is the number of char str1[15] = “Hello, ”;
characters in the string, not counting char str2[7] = “World!”;
the terminating null character int length = 0;

• Syntax: strlen(<s1>) length = strlen(str1);


printf(“%d”, length);
strcat(str1, str2);
printf(“%s”, str1);
• Output: length = strlen(str1);
7 printf(“%d”, length);
Hello, World!
13
strlwr
(string lower)
• Converts a string s to all lowercase • Example:
• Syntax: strlwr(<s>); char str1[15] = “Hello, WORLD!”;

strlwr(str1);
puts(str1);

• Output: hello, world!


strupr
(string upper)
• Converts a string s to all uppercase • Example:
• Syntax: strupr(<s>); char str1[15] = “Hello, WORLD!”;

strupr(str1);
puts(str1);

• Output: HELLO, WORLD!


strrev
(string reverse)
• Reverses all characters in string s • Example:
except for the terminating null
character char str1[15] = “Hello, WORLD!”;

• Useful in detecting palindromes strrev(str1);


puts(str1);
• Syntax: strrev(<s>);

• Output: !DLROW ,olleH


END OF PRESENTATION

You might also like