Module4 Chapter1
Module4 Chapter1
MODULE – 4
Strings and Pointers: Introduction, string taxonomy, operations on strings, miscellaneous string
and character functions, arrays of strings.
Pointers: Introduction to pointers, declaring pointer variables, Types of pointers, passing arguments
to functions using pointers.
CHAPTER 1 STRINGS
In C language, a string is a null-terminated character array. This means that after the last
character, a null character ('\0') is stored to signify the end of the character array.
For example, if we write char str[] = "HELLO"; then we are declaring an array that has five
characters, namely, H, E, L, L, and O.
Apart from these characters, a null character ('\0') is stored at the end of the string. So, the
internal representation of the string becomes HELLO'\0'.
To store a string of length 5, we need 5 + 1 locations (1 extra for the null character).
The name of the character array (or the string) is a pointer to the beginning of the string.
C does not support strings as a data type. However, it allows us to represent strings as character
arrays in C, therefore, a string variable is any valid C, variable name and is always declared as an
array of characters.
char string_name[size];
char name[30];
When the compiler assigns a character string to a character array, it automatically supplies a null
character ('\0') at the end of the string. Therefore, the size should be equal to the maximum
number of characters in the string plus one.
Like numeric arrays, character arrays may be initialized when they are declared.
char city [9]={‘N’, ‘E’, ‘W’,’ ‘,‘Y', '0', 'R', 'K', '\0'};
The reason that city had to be 9 elements long is that the string NEW YORK contains 8
character and one element space is provided for the null terminator.
Without size
For example, the statement char string [ ] = {‘G’, ‘O’,’O’, ‘D’,'\0'}; defines the array
string as a five element array.
Partial Initialization
We can also declare the size much larger than the string size in the initializer. That is, the
statement. char str[10] = "GOOD"; is permitted. In this case, the computer creates a
character array of size 10, places the value "GOOD" in it, terminates with the null
character, and initializes all other elements to NULL. The storage will look like:
G O O D \0 \0 \0 \0 \0 \0
However, the following declaration is illegal. char str2[3] = "GOOD"; This will result in a
compile time error.
Also note that we cannot separate the initialization from declaration. That is,
char str3[5];
str3 = "GOOD";
char s2[4];
s2 = sl; /* Error */
is not allowed.
2. gets() function
The input function scanf can be used with %s format specification to read in a string of
characters.
scanf("%s", address);
The problem with the scanf function is that it terminates its input on the first white space it
finds. A white space includes blanks, tabs, new lines etc.,
NEW YORK
then only the string "NEW" will be read into the array address, since the blank space after the
word 'NEW' will terminate the reading of string. The scanf function automatically terminates the
string that is read with a null character and therefore the character array should be large enough
to hold the input string plus the null character.
Unlike previous scanf calls, in the case of character arrays, the ampersand (&) is not required
before the variable name.
#include<stdio.h>
void main()
char name[20];
printf(“Enter a name”);
scanf(“%s”,name);
printf(“Name is %s”,name);
Output:
Name is bala
C supports a format specification known as the %[..] that can be used to read a line containing a
variety of characters, including whitespaces.
For example.
char line[80];
scanf(“%[^\n]”,line);
printf(“%s”,line);
will read a line of input from the keyboard and display the same on the screen.
The getchar function is used to read a single character. It takes the form :
char ch;
ch=getchar( ) ;
We can use this function repeatedly to read successive single characters from the input and place
them into a character array. Thus, an entire line of text can be read and stored in an array.
The reading is terminated when the newline character (“\n”) is entered and the null character is
then inserted at the end of the string.
Program :
Write a program to read a line of text (use getchar) containing a series of words from the
terminal.
#include<stdio.h>
void main( )
{
char line[80], character;
int i=0;
do
{
character = getchar();
line[i] = character;
i++;
}
while(character != '\n');
line[i] = '\0';
printf("\n%s\n", line);
}
Output
Programming in C is interesting.
Programming in C is interesting.
3. Using gets() function
This is a function with one string parameter and called as under:
gets (str);
str is a string variable declared properly. It reads characters into str from the keyboard until a
new-line character is encountered and then appends a null character to the string. Unlike scanf, it
does not skip whitespaces. For example the code segment
char 1ine [80] ;
gets (1ine);
printf ("%s", line);
reads a line of text from the keyboard and displays it on the screen.
Write a program to input and output a name
#include<stdio.h>
void main()
char name[20];
printf(“Enter a name”);
gets(name);
printf(“Name is %s”,name);
Output:
Program :
Write a program to find the number of vowels and consonants in a text string.
#include<stdio.h>
#include<string.h>
int main()
{
int i,vc=0,cc=0;
char s[100],ch;
printf(“\n Enter the sentence”);
gets(s);
for(i=0;i<strlen(s);i++)
{
if(isalpha(s[i]))
{
ch=tolower(s[i]);
if(ch==’a’||ch==’e’||ch==’i’||ch==’o’||ch==’u’)
vc++;
else
cc++;
}
}
printf(“\n Vowel count=%d\n”,vc);
printf(“\n Consonant count=%d\n”,cc);
return 0;
}
Test cases
puts(line);
reads a line of text from the keyboard and displays it on the screen.
Write a program to input and output a name
#include<stdio.h>
void main()
char name[20];
printf(“Enter a name”);
gets(name);
puts(“Name is”);
puts(name);
Fixed-length strings
When storing a string in a fixed-length format, we need to specify an appropriate size for the
string variable.
If the size is too small, then we will not be able to store all the elements in the string.
If the size is large, then unnecessarily memory space is wasted.
Variable-length strings
We can use a variable length format in which the string can be expanded or contracted to
accommodate the elements in it.
To use a variable length string format we need a technique to indicate the end of the elements
that are a part of the string. This can be done either by using length-controlled string or a
delimiter.
Length-controlled strings In a length-controlled string, we need to specify the number of
characters in the string.
Delimited strings 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(.). Null character is the most commonly used string delimiter in the C language.
is a valid statement. In ASCII, the value of ‘x’ is 122 and therefore, the statement will
assign the value 121 to the variable x.
We may also use character constants in relations expressions. For example , the
expression
ch >= ‘A’ && ch <=’Z’
would test whether the character contained in the variable ch is an upper case letter.
We can convert a character digit to its equivalent integer value using the following
relationship:
x = character - '0';
where x is defined as an integer variable and character contains the character digit. For
example, let us assume that the character contains the digit '7', Then
x = ASCII value of ‘7’- ASCII value of '0'
= 55-48
=7
The C library supports a function that converts a string of digits into their integer values.
The function takes the form
x = atoi(string);
x is an integer variable and string is a character array containing a string of digits.
Consider the following segment of a program:
char number[5] = "1988";
year = atoi(number);
number is a string variable which is assigned the string constant "1988". The function
atoi converts the string "1988" (contained in number) to its numeric equivalent 1988 and
assigns it to the integer variable year. String conversion functions are stored in the header
file <stdlib.h>
Program :
Write a program which would print the alphabet set a to z and A to Z in decimal and character
form.
void main()
{
char c;
gets(s2);
while(s1[i]!='\0')
{
s3[i]=s1[i];
i++;
}
s3[i]=' ';
while(s2[j]!='\0')
{
s3[i+1+j]=s2[j];
j++;
}
s3[i+1+j]='\0';
printf("Concatenated string is %s",s3);
}
Output:
Enter string1: good
Enter string2: girl
Concatenated string is good girl
2. COMPARISON OF TWO STRINGS
Once again, C does not permit the comparison of two strings directly. That is, the statements
such as
if(namel == name2)
if(name == "ABC")
are not permitted. It is therefore necessary to compare the two strings to be tested, character by
character. The comparison is done until there is a mismatch or one of the strings terminates into a
null character, whichever occurs first. The following segment of a program illustrates this.
Program : compare two strings without using library function
#include<stdio.h>
void main()
{
char s1[20],s2[20];
int i=0,k;
printf("Enter string1: ");
gets(s1);
printf("Enter string2: ");
gets(s2);
while(s1[i]==s2[i])
{
if(s1[i]=='\0')
break;
i++;
}
k=s1[i]-s2[i];
if(k==0)
printf("Strings are same");
else
printf("Strings are different");
}
Output:
Enter string1: good
Enter string2: good
Strings are same
3. STRING LENGTH
The length of the string can be found by counting character by character until the null character.
Program : Length of the string without a library function
#include<stdio.h>
void main()
{
char s1[20];
int i=0;
printf("Enter a string: ");
gets(s1);
while(s1[i]!='\0')
{
i++;
}
printf("Length of the string is %d",i);
}
Output:
Enter a string: good
Length of the string is 4
4. STRING COPY
We cannot assign one string to another directly, we can copy a string to another character by
character.
Program : String copy without a library function
#include<stdio.h>
void main()
{
char s1[20],s2[20];
int i=0;
printf("Enter a string: ");
gets(s1);
while(s1[i]!='\0')
{
s2[i]=s1[i];
i++;
}
s2[i]='\0';
printf("Copied string is %s",s2);
}
Output:
Enter a string: hello girl
int main() {
char s1[50],s2[50];
{
int i=0, j=0,n=0;
char s1[50],s2[50];
printf ("Enter a string: ");
int i = 0, j =0;
gets(s1);
printf ("Enter a string: ");
while(s1[n]!=’\0’)
gets(s1);
{
for(j=strlen(s1)-1;j>=0;j--)
n++;
{
}
s2[i] = s1[j];
i++; for(j=n-1;j>=0;j--)
} {
s2[i] = s1[j];
printf ("The reversed string is %s", s2);
i++;
return 0;
}
}
printf ("The reversed string is %s", s2);
Output:
return 0;
Enter a string: good
}
The reversed string is doog
1.5 MISCELLANEOUS STRING AND CHARACTER FUNCTIONS [STRING
HANDLING FUCTIONS]
1.5.1 Character Manipulation Functions
Some character functions are contained in the file ctype.h and therefore the statement #include
<ctype.h> is included in the program.
Fortunately, the C library supports a large number of string-handling functions that can
be used to carry out many of the string manipulations. Following are the most commonly used
string handling functions (stored in header file string.h).
S:No Function Action
1 strcat( ) Concatenates two strings
2 strncat() Concatenates first leftmost n characters of string2 to
string1
3 strcmp( ) Compares two strings
4 strncmp() Compares first leftmost n characters in both strings
5 strcpy( ) Copies one string over another
6 strncpy() Copies first leftmost n characters of source string to
target.
7 strlen( ) Finds the length of a string
8 strrev() Reverses a string
9 strstr() Searches for string2 in string1
10 strchr() Locate the first occurrence of the character
11 strrchr() Locate the last occurrence of the character
1. strcat( ) Functions
The strcat functions joins two strings together. It takes the following form:
strcat(string1,string2);
string1 and string2 are character arrays. When the function strcat is executed, string2 is appended
to string1.It does so by removing the null character at the end of string1 and placing string2 from
there.
The string at string2 remains unchanged. For example, consider the following three strings:
We must make sure that the size of string1 (to which string2 is appended) is large enough to
accommodate the final string.
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
printf("Enter string1:");
gets(s1);
printf("Enter string2:");
gets(s2);
strcat(s1,s2);
printf("concatenated string is %s",s1);
}
Output:
Enter string1:good
Enter string2: girl
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
printf("Enter string1:");
gets(s1);
printf("Enter string2:");
gets(s2);
strncat(s1,s2,4);
printf("concatenated string is %s",s1);
}
Output:
Enter string1:good
Enter string2:girls
concatenated string is goodgirl
3. strcmp() Function
The strcmp function compares two strings and returns value 0 if they are equal. If they are not, it
has the numeric difference between the first nonmatching characters in the strings. It takes the
form:
strcmp(string1, string2);
string1 and string2 may be string variables or string constants.
Examples are:
strcmp(namel, name2);
strcmp(namel, "John");
strcmp("Rom", "Ram");
For example, the statement
strcmp("their", "there");
will return a value of -9 which is the numeric difference between ASCII "i" and ASCII "r". That
is, "i" minus "r" in ASCII code is -9. If the value is negative, string1 is alphabetically above
string2.
returns 0 If both strings are same
returns negative If string1 is alphabetically above string2
(string1<string2)
returns positive If string1 is alphabetically below string2
(string1>string2)
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
int k;
printf("Enter string1:");
gets(s1);
printf("Enter string2:");
gets(s2);
k=strcmp(s2,s1);
if(k==0)
printf("same strings");
else
printf("not same");
}
Output:
Enter string1:good
Enter string2:good
same strings
4. strncmp Function
This function has three parameters as illustrated in the function call below:
strncmp (sl, s2, n);
this compares the left-most n characters of s1 to s2 and returns.
(a) 0 if they are equal;
(b) negative number, if s1 sub-string is less than s2(alphabetically above); and
(c) positive number, otherwise.
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
int k;
printf("Enter string1:");
gets(s1);
printf("Enter string2:");
gets(s2);
k=strncmp(s2,s1,5);
if(k==0)
printf("same strings");
else
printf("not same");
}
Output:
Enter string1:hello dad
Enter string2:hello world
Same strings
5. strcpy( ) Function
The strcpy function works almost like a string-assignment operator.
It takes the form:
strcpy(string1, string2);
and assigns the contents of string2 to string1. string2 may be a character array variable or a
string constant. Here string1 is target and string2 is source.
For example, the statement
strcpy(city, "DELHI");
will assign the string "DELHI" to the string variable city.
Similarly, the statement
strcpy(cityl, city2);
will assign the contents of the string variable city2 to the string variable city1. The size of the
array city1 should be large enough to receive the contents of city2.
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
printf("Enter a string:");
gets(s1);
strcpy(s2,s1);
printf("Copied string is %s",s2);
}
Output:
Enter a string:hello girl
Copied string is hello girl
6. strncpy Function
strncpy() function that copies only the left-most· n characters of the source string to the target
string variable. This is a three-parameter function. strncpy(sl, s2, n); where n is a integer.
strncpy(sl, s2, 5);
This statement copies the first 5 characters of the source string s2 into the target string s1.
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
printf("Enter a string:");
gets(s1);
strncpy(s2,s1,5);
printf("Copied string is %s",s2);
}
Output:
Enter a string:hello girl
Copied string is hello
7. strlen( ) Function
This function counts and returns the number of characters in a string. It takes the form
n = strlen(string);
Where n is an integer variable, which receives the value of the length of the string. The argument
may be a string constant. The counting ends at the first null character. strlen() gives the length
of the string excluding the null character.
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20];
int n;
printf("Enter a string:");
gets(s1);
n=strlen(s1);
printf("Length of the string is %d",n);
}
Output:
Enter a string:good
Length of the string is 4
8. strrev( ) Function
This function reverses the string. It takes the form: strrev(string); The reversed string is stored in
the string itself.
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20];
printf("Enter a string:");
gets(s1);
strrev(s1);
printf("Reversed string is %s",s1);
}
Output:
Enter a string:good
Reversed string is doog
9. strstr Function
It is a two-parameter function that can be used to locate a sub-string in a string.
This takes the forms: strstr (sl, s2);
strstr (sl, "ABC");
The function strstr searches the string s1 to see whether the string s2 is contained in s1. If yes,
the function returns the position of the first occurrence of the sub-string. Otherwise, it returns a
NULL.
Example.
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20],s2[20];
printf("Enter string1: ");
gets(s1);
printf("Enter string2: ");
gets(s2);
if (strstr (s1, s2) == NULL)
printf("substring is not found");
else
printf("s2 is a substring of s1");
}
Output:
Enter string1:good for good
Enter string2:for
s2 is a substring of s1
10. strchr Function
It is a two-parameter function that can be used to determine the existence of a character in a
string.
This takes the form: strchr(s1,’m’); will locate the first occurrence of the char ‘m’ in the string
s1.
#include<stdio.h>
#include<string.h>
void main()
{
char s1[20];
char *pos;
printf("Enter a string: ");
gets(s1);
pos=strchr(s1,'n');
if(pos)
printf("First occurrence of the character is found at %d",pos);
else
#include<stdio.h>
#include<string.h>
void main()
char s1[20],s2[20];
printf("Enter a string:");
gets(s1);
strcpy(s2,s1);
strrev(s2);
if(strcmp(s1,s2)==0)
printf("string is a palindrome");
else
Output:
string is a palindrome
List of character strings can be stored in a 2-D character array. We often use list of names of
students in a class, list of cities etc.
Ex – name[3][10];
r a m \0
r a v i \0
r a m y a \0
DECLARATION:
char array_name[row_size][col_size];
INITIALIZATION
Arrays of strings may be initialized (given initial values) when they are declared.
2 types of initialization -
1) char name[3][10]={“ram”,”ravi”,”ramya”};
name[0]=”ram”
name[1]=”ravi”
name[2]=”ramya”
2) without size
char name[][10]={“ram”,”ravi”,”ramya”};
To access
Each name only row index is used , (i.e) to access ith name - name[i] is used.
Each character both row and column index is used , (i.e) to access i th name jth character
name[i][j] is used.
for(i=0;i<n;i++)
scanf(“%s”,name[i]);
(or)
for(i=0;i<n;i++)
gets(name[i]);
for(i=0;i<n;i++)
printf(“\n%s”,name[i]);
(or)
for(i=0;i<n;i++)
puts(name[i]);
void main()
int n,i;
char name[10][20];
printf(“enter n”);
scanf(“%d”,&n);
printf(“enter names”);
for(i=0;i<n;i++)
gets(name[i]);
printf(“names are”);
for(i=0;i<n;i++)
printf(“\n %s”,name[i]);
}
Lab Program
Write functions to implement string operations such as compare, concatenate, and find
string length. Use the parameter passing techniques.
Program
#include<stdio.h>
int strlength(char str1[50]);
void strconcat(char str1[50],char str2[50]);
int strcompare(char str1[50],char str2[50]);
int strlength(char str[50])
{
int i=0;
while(str[i]!='\0')
i++;
return i;
}
void strconcat(char str1[50],char str2[50])
{
int i=0,l;
l=strlength(str1);
while(str2[i]!='\0')
{
str1[l+i]=str2[i];
i++;
}
str1[l+i]='\0';
}
int strcompare(char str1[50],char str2[50])
{
int i=0,k;
while(str1[i]==str2[i])
{
if(str1[i]=='\0')
break;
i++;
}
k=str1[i]-str2[i];
return k;
}
int main()
{
char source1[50],source2[50];
int length1,length2,k;
printf("\n Enter the source string 1:");
gets(source1);
printf("\n Enter the source string 2:");
gets(source2);
length1=strlength(source1);
length2=strlength(source2);
printf("\n string length of string 1 is %d",length1);
printf("\n string length of string 2 is %d",length2);
k=strcompare(source1,source2);
if(k==0)
printf("\n Both string are same");
else
printf("\n Both string are different");
strconcat(source1,source2);
printf("\n concatenated string is ");
puts(source1);
return 0;
}
Test cases
2 is 4 2 is 4
Both strings are same Both string are same
concatenated string is concatenated string is
goodgood goodgood
2 Enter the source string1 :good string length of string string length of string
Enter the source string 2:girls 1 is 4 1 is 4
string length of string string length of string
2 is 5 2 is 5
strings are different strings are different
concatenated string is concatenated string is
goodgirls goodgirls