Chapter 5
Exploring Strings
Strings
• A string is defined as null terminated character array.
• A string must be terminated by a null – means that we need one
byte extra for holding null character.
• A string constant is null-terminated by the compiler automatically.
• Each character takes one byte in string.
Read Strings from Keyboard
• There are several ways-
• Using scanf() function-
• for string C use “%s” format specifier.
• Word
• Sentence
• Safest
• Most common is: gets(). The major drawback of gets() is that it does not
check the length of the input string. It's recommended to use fgets() instead,
which allows you to limit the number of characters that can be read.
gets()
• C’s standard library function
• uses the STDIO.H header file
• To use – call it using the name of a character array without
any index.
char str[100];
gets(str);
• get() function reads character until we press ENTER
• The ENTER key (carriage return - \r) is not stored, but is
replaced by a null, which terminates the string.
gets() …
page 145
Here null is false
to control the loop
that output the string
gets() - Be aware!
• The get() function performs no bounds checking.
• It is possible to enter more characters than the array
receiving them can hold – unwanted result!
• For example, if we call gets() with an array that is 20
characters long, there is no mechanism to stop us from
entering more than 20 character.
puts()
• C’s standard library function
• uses the STDIO.H header file
• To use – call it using the name of a character array without
any index.
char str[100] = “This is it”;
puts(str);
puts()
Example
Initialize String
Example
STRING.H
• The four most string related library functions are
1. strcpy() – for copy
2. strcat() – for concatenation
3. strcmp() – for compare two strings
4. strlen() – for finding length of a string
strcpy()
strcpy (to, from);
• It copies the contents of from to to.
strcpy()
String – strcpy 1
strcpy()
String – strcpy 2
strcat()
strcat (to, from);
• adds the contents of one string (from) to another (to).
strcat()
strcat()
strcmp()
strcmp(s1,s2);
• It returns zero – if s1 and s2 same (s1 = s2)
• It returns less than zero – if s1 less than s2 (s1 < s2)
• It returns greater than zero – if s1 greater than s2 (s1 > s2)
strcmp()
Example 1
Example 2
strlen()
strlen (str);
• returns the length, in characters of a string.
• It does not count the null terminator
strlen()
Example