ICS 103: Computer Programming in C
Handout-15
Topic:
Strings
Instructor:
M. Waheed Aslam.
Objectives:
·
To know what is string and
how to handle it?
·
To know how to Read and
Print Strings.
·
To know about some important
built-in string functions and how to use them?
·
A
string is any sequence of
characters enclosed in double
quotes.
·
There
is no separate data type for strings as integer,
float or double.
·
The
string data type can be considered as a char array.
§
The
difference is that a character variable can hold only one character but a string can have more than one character in a character array.
§
For
example, a string called name with 9 characters can be declared as:
char name
[9] = “I like C”;
Ø
Check
for the double quotes, the char array size 9.
Ø
Here
the name can be considered as one
string or as an array of characters.
Ø
That
is if you refer name it is “I like C” and if you refer name[0] it is ‘I’, name[1] is ‘ ‘ (a blank),
name[2] is ‘l’, name[3] is ‘i’, and so on.
Ø
The
last character name[8] is ‘\0’ which indicates a NULL character which is not
displayed but is stored as last character of the string to indicate its end.
Note: Strings are stored as
arrays of characters and have a special ‘\0’
termination character called NULL appended (attached) to them to signify
the end of the string.
·
Note that if the number of
characters including the ‘\0’ is more
than the size of the array the results will be unpredictable.
·
However,
if the size of the array is more than the number of characters the extra spaces
after the last ‘\0’ character are
kept blank and not referred because the string ends at ‘\0’.
·
So, always make sure that the size of the array is sufficient
for the string.
For example,
the above declaration would be wrong if we write
char name
[8] = “I like C”;
·
The
size can also be ignored. In that case the size is considered as that of the
number of characters specified in the declaration.
char name
[ ] = “I like C”;
·
The
easiest way to input strings is by using the C library function gets (means get string).
·
The
gets( ) function reads a string of
characters entered at the keyboard until you strike the enter key (carriage
return).
·
The
carriage return does not become part of the string; instead a null terminator ‘\0’ is placed at the end.
For example, in the following program fragment
char str[80];
gets (str);
and
if the user enters
Computer Programming
in C
and
presses the enter key the string variable str
has the characters “Computer Programming in C”
with ‘\0’ appended at the end
but is not displayed.
·
Similarly,
there is an output function puts ( )
which prints or displays the value of the string variable. Unlike the printf, which stays on the same line
after printing puts automatically
advances the output to the next line after displaying it.
puts (str);
Example:
char
name [81] = {“ Computer Programming in
C ”};
gets (name); /* reads the name */
puts (name); /* prints the name */
·
You
can also use the scanf function for
string input by means of the %s
format specifier and the printf
function for string output. But the disadvantage with it is that scanf interprets a blank as the end
of the particular input value.
·
As
a result you can’t read the above line
Computer Programming in C with scanf using a single string variable.
·
You
need to take 4 string variables to read the 4 words as
char first[12], second[12], third[12],
fourth[12];
scanf
(“%s %s %s %s”, first, second, third, fourth);
printf (“This course is: %s %s %s %s\n”, first, second, third,
fourth );
·
Note
that there is no & (address of) operator for string
variables when they are read with scanf.
Built-in String Functions:
·
A
large collection of string processing functions are provided in C through string.h file.
·
So,
include the string.h file in the programs
to use these functions.
·
To
use the string functions make sure that the size of the array is sufficient
so that the strings are terminated with the ‘\0’ character or the functions will not work properly.
strcat ( string1,
string2 )
·
The
strcat function concatenates
or joins the string1 and string2. A copy of string2 is put at the end of the string1. Make sure that string1
size is long enough to hold the resulting string (string1 + string2).
Example:
char string1[ 81] = “abc”, string2 [ ] = “def”;
strcat ( string1, string2);
puts
( string1 );/*
outputs “abcdef” which is stored in string1 */
strcpy (
string1, string2 )
·
The
strcpy function copies string2 into string1. Again make sure that string1
size is long enough to hold the resulting string.
Example:
char string1 [ 81]
, string2 [ ] = “memory”;
strcpy ( string1, string2 );
Puts ( string1 ); /* outputs “memory”
copied into string1 */
strcmp ( string1, string2 )
·
The
strcmp function compares the string1 to string2 and returns an integer value to show the status of the
comparison.
·
A
value of 0 indicates that the two
strings are identical.
·
A
value of less than 0 shows that string1 is lexicographically (according
to alphabetic ordering) less than string2.
·
A
value of greater than 0 shows that
string1 is lexicographically (according to alphabetic ordering) greater
than string2.
Example:
char string1 [ ] = “John Doe”;
char string2 [ ] =
“John Doe”;
char string3 [ ] =
“Jane Doe”;
char string4 [ ] =
“John Does”;
printf ( “%d %d %d”, strcmp (string1, string2), strcmp
(string1,
string3), strcmp (string1,
string4)); /*
outputs 0, >0, <0 */
·
Note
that when the strings are not equal the result is positive or negative and
not the exact value.
strlen ( string1 ):
·
The
strlen function returns an integer
equal to the length of the
stored string including blanks, not including the termination character.
Example:
char
string1 [81] ;
char string2 [ ] = “Jane
Doe”;
printf (“%d %d”, strlen ( string1 ),
strlen ( string2 ));
/* outputs 0 for string1, 8 for string2 */
strchr ( string, ch ) :
·
The
strchr function searches string for the first occurrence of ch.
·
This
function only tells whether the string contains ch or not and it will not tell the position of the ch in the string if found.
Example:
char string [9] = “John Doe”;
char search = ‘D’;
if ( strchr (string,
search ) != NULL )
printf (“Search
character found\n”);
/*outputs this message */
else
printf (“Search character not found\n”);
Solved
Problems:
/*************************************************************
Problem #1:
Write a program that initializes a character
array first of size 20,
character array last
of size 20 and array full of character of size
40
Array first contains the first name ,
array last contains the last name,
array full joins the two strings
together first and last .
*************************************************************/
#include<stdio.h>
#include<string.h>
void main()
{
char first[20];
char last[20];
printf("Plz Enter your first name
with space at the end:");
gets(first);
printf("Plz Enter your last
name:"); gets(last);
strcat(first, last); // it joins last into first
printf("\nYour full name is: ");
puts(first);
} // end of
main
Sample Output:
/************************************************************
Program #2:
Write a program that uses 5 strings str1,
str2, str3, str4, str5 each of size 81.
Let str1="what", str2 =
"whatsoever, str3 = "ever", str4 = "whatever".
Then it should do the following:
Join str3 to str1 and print str1.
Copy str1 to str5 and print str5.
Compare str5 and str4 and print whether they are equal or not.
Find the length of the string str1 and print it.
Check whether the character 'w' occurs in
both the strings str2 and str3
and print "Yes" if it occurs
in both, else print "No".
Use puts ( ) function for printing strings.
*/
#include<stdio.h>
#include<string.h>
void main()
{
int
i, length_str1;
char str1[81]="what";
char str2[81]="whatsoever";
char str3[81]="ever";
char str4[81]="whatever";
char str5[81];
strcat(str1,str3); // it joins str3 with str1 and assigns result in str1.
puts("After joining str3 with str1 ,
the new str1 is :");
puts(str1);
strcpy(str5,str1); // it copies
str1 into str5.
puts("After coping str1 into str5,
the new str5 is :");
puts(str5);
i=strcmp(str5,str4); // it returns 0 when str5 and str4 are equal.
if(i==0)
puts("The str5 and str4 are
equal");
else
puts("The str5 and str4 are not
equal");
length_str1=strlen(str1); //it calculates length of str1.
printf("The length of str1 is : %d
",length_str1);
if(strchr(str2,'w')!=NULL &&
strchr(str3,'w')!=NULL)
puts("\nYes");
else
puts("\nNo");
} // end of
main
Sample Output:
Character related
standard Library Functions in C:
C provides a family of
character-related Standard functions that facilitate character manipulations.
To use these functions, #include <ctype.h> header file is used.
List of character related functions is given
below:
Name |
Description |
Example |
Return |
isalnum |
Tests for alphanumeric |
isalnum(‘a’) |
1 |
isalpha |
Tests for alphabetic |
isalpha(‘a’) |
1 |
iscntrl |
Tests for control
character |
iscntrl(‘\n’) |
1 |
isdigit |
Tests for digit |
isdigit(‘1’) |
1 |
islower |
Tests for lowercase
charter |
islower(‘a’) |
1 |
isupper |
Tests for uppercase
character |
isupper(‘A’) |
1 |
ispunct |
Test for punctuation
character |
ispunct(‘!’) |
1 |
isspace |
Tests for whitespaces
charcter |
isspace(‘ ‘) |
1 |
toupper |
Converts characters
to uppercase |
toupper(‘a’) |
A |
tolower |
Converst characters
to lowercase |
tolower (‘A’) |
a |
Sample Output:
Example:
#include
<stdio.h> #include
<ctype.h> int
main(void) { int i,countup,countlow; int
countspace,countdigit,countpunc,countcontrol_c; char str[80] = "\n\t\tICS 103 Computer Programming in C ! .
\n"; i=countup=countlow=countspace=countdigit=countpunc=countcontrol_c=0; while(str[i] !='\0') { if(ispunct(str[i])) countpunc++; if(iscntrl(str[i])) countcontrol_c++; if(isdigit(str[i])) countdigit++; if(isspace(str[i])) countspace++; if(isupper(str[i])) countup++; if(islower(str[i])) { countlow++; str[i] =
toupper(str[i]); } i++; } printf("The number of digits =
%d\n",countdigit); printf("The number of spaces =
%d\n",countspace); printf("Upper case letters =
%d\n", countup); printf("Lower case letters =
%d\n", countlow); printf("Punctuation
characters = %d\n",countpunc); printf("Total control characters =
%d\n", countcontrol_c); printf("%s\n", str); return 0; }
|
Sample Output:
Example:
Solution:
/* prints the number of vowels, upercase & lowercase in a
main ( )
}
Sample Output: