Documente Academic
Documente Profesional
Documente Cultură
Strings in 'C'
There is no String type in 'C' so you can't declare it like an integer.
Instead strings are stored as an array of characters terminated by a "null zero". We will
learn more about arrays later in the course.
An array is just the individual characters in the string being stored together in memory. A
character array is nothing more than a list of characters.
A 'null zero' lets the computer know when you have finished your string. We use '\0' to
denote a null zero. It is called a "string terminator".
Note that it is different than the character zero. So you can have the string, "June 30,
2020".
H e l l o \0
So the string "Hello" above takes 6 characters to store. One plus the length of the string.
STRCMP
The string compare function uses the following syntax:
char s1[10];
char s2[10];
int result;
result = strcmp(s1,s2);
STRLEN
Strlen() returns the an integer stating the length of the string, not including the null
character at the end of the string.
Questions:
What appears, internally at the end of every string?
How would you declare a variable to hold the string "Lisgar" with the least amount of
memory allocated?
Exercises:
1. Write a program that initializes two strings to your first and last names, and prints
them out, last name first.
2. Have the program read in your name. Allow 20 characters for first and last name.
3. Declare two strings s1, s2 as "Larry" and "Moe". Allow each name to hold 5
characters. Switch the contents of s1 and s2.
[Save as LASTNAME_Firstname Unit 1 Larry Moe]
ICS3U Lesson 6 Using Strings In C Page 3 of 3
4. Write a program that will read in 2 chars and print them in alphabetically order. The
syntax for the "if" statement is:
5. Write a program that will read in 2 strings that have a maximum of 30 characters and
print: [Save as LASTNAME_Firstname Unit 1 Longest String]
a. The longest one first
b. In alphabetically order
7. Enrichment exercise:
a. Ask the user for two strings, determine if one string is contained in the other.
For example: "ample" "Example"
Print out "ample is contained in Example"
IF STATEMENT IN C
int n1 = 1;
int n2 = 2;
if ( n1 == n2) {
printf("They are equal");
}
else if (n1 > n2) {
printf("The first number is larger");
}