Module 4
MODULE – 4
STRING
String :
A string constant can be defined as a sequence of characters enclosed within double quotes
followed by a null character(‘\0’).
Eg: “bhavya”.
Declaration:
char string_name[string_size];
Where,
char is the datatype of string
string_name is name of string
string_size is length of string
Initialization of string :
1. Consider an example
char str[10]=”HELLO”
H E L L O \0 \0 \0 \0 \0
str[0] str[1] str[2] str[3] str[4] str[5] str[6] str[7] str[8] str[9]
Here, compiler creates a character array of size 10, stores “HELLO” in it. Rest of the
elements is initialized to “null”.
2. Consider an example
char str[]=”HELLO”
H E L L O \0
str[0] str[1] str[2] str[3] str[4] str[5]
Here, compiler will automatically calculate the size of string based on the number of
elements initialized.
Bhavya P S.,Asst prof.,KVGCE Page 1
Module 4
Reading string:
The string can be read by using three ways:
1. Using scanf() statement:
The string can be read by using scanf() statement as
Eg :
char str[10];
scanf(“%s”,str);
2. Using gets() function:
The string can be read by using gets() statement as
Eg :
char str[10];
gets(str);
3. Using getchar(), getch(), getche():
The string can be read by getchar(), by calling getchar() repeatedly.
Eg :
i=0;
getchar(ch);
while(ch!=’\n’)
{
str[i]=ch;
i++;
getchar(ch);
}
str[i]=’\0’;
Writing strings:
The string can be displayed on screen by using three ways.
1. Using printf() function:
The string can be displayed by using printf() statement as
Eg:
char str[]=“HELLO”;
printf(“%s”, str);
2. Using puts() function:
The string can be displayed by using puts() statement as
Eg:
char str[]=“HELLO”;
puts(str);
3. Using putchar() function repeatedly.
Bhavya P S.,Asst prof.,KVGCE Page 2
Module 4
The string can be displayed by using putchar() statement as
Eg:
i=0;
while(str[i]!=’\0’)
{
putchar(str[i]);
i++;
}
Summary of functions used to read and write characters:
1. getchar():
It is a standard function.
It is used to read a character from keyboard.
2. getch():
It is non standard function.
It is used to read a character from keyboard.
Does not echo to screen.
3. getche():
It is non standard function.
It is used to read a character from keyboard.
It echoes to screen.
4. putchar():
It is a standard function.
It is used to write a character to the screen.
Suppressing a input using a scanset:
A scanset is used to define a set of characters which may be read and assigned to the
corresponding string.
A scanset is defined by placing the characters inside square brackets prefixed with a %.
Example:
#include<stdio.h>
main()
{
char str[10];
printf(“enter a string\n”);
scanf(“%[aeiou]”,str);
printf(“the string is %s”, str);
}
Bhavya P S.,Asst prof.,KVGCE Page 3
Module 4
In this code, it will stop accepting a character as soon as the user enters a character that is
not vowel.
String taxonomy:
In C, we can store a string either fixed format or in variable length-format as shown below.
Fixed-length string:
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 it is not possible to store all the elements and if the
size is large, them unnecessary memory space will be wasted.
Variable length format:
In this format the string can be expanded or contracted to accommodate the elements in it. Here,
we should indicate the end of elements that are part of the system. This can be done either by
length – controlled string or a delimiter.
Length controlled string:
In this, we need to specify the number of characters in the string.
Delimited string:
In this format, the string is ended with a delimiter. The delimiter is then used to identify the end
of the program.
Operations performed on string:
1. Length
2. Converting characters of a string into uppercase
3. Converting characters of a string into lowercase
4. Concatenating two strings to form a new string
5. Comparing two strings
6. Reversing a string
7. Copying one string to another
Bhavya P S.,Asst prof.,KVGCE Page 4
Module 4
Miscellaneous string and character functions:
1. Character manipulation functions:
Function Usage Example
isalnum(int c) Checks whether character c is an alphanumeric isalnum(‘A’);
character
isalpha(int c) Checks whether character c is an alphabetic isalha(‘z’);
character
iscntrl(int c) Checks whether character c is a control iscntrl(c)
character
isdigit(int c) Checks whether character c is a digit isdigit(3)
isgraph(int c) Checks whether character c is a graphic isgraph(‘!’)
character
islower (int c) Checks whether character c is a lowercase islower(‘k’)
character
isprint(int c) Checks whether character c is a printing isprint(‘@’)
character
isupper(int c) Checks whether character c is an uppercase isupper(‘J’)
character
ispunct(int c) Checks whether character c is a punctuation ispunct(‘?’)
character
isspace(int c) Checks whether character c is a white space isspace(‘ ‘)
character
isxdigit(int c) Checks whether character c is a hexadecimal isxdigit(‘F’)
character
tolower(int c) Converts a character to lowercase tolower(‘K’)
toupper(int c) Converts a character to uppercase toupper(‘k’)
2. String manipulation functions:
Function Description
strlen() Returns number of characters in the given string
strcpy() Copy the given source string to another destination string
strcmp() Compare two strings for their similarity
strcat() Joins two strings into a singlw string
strupr() Converts characters into uppercase
strlwr() Converts characters into lowercase
strrev() Reverse the given string
Bhavya P S.,Asst prof.,KVGCE Page 5
Module 4
strlen():
This function will count the number of characters in the string until it reaches the null character
and returns the integer value as output.
Syntax: strlen(str);
Example:
#include<stdio.h>
#include<string.h>
main()
{
char str[20];
int len;
printf(“enter the name”);
gets(str);
len=strlen(str);
printf(“the length of the string is %d”,len);
}
Output:
enter the name
hello
the length of the string is 5
strcpy():
It is used to copy one string to another string.
Syntax: strcpy(str1,str2)
Str1: destination string
Str2: source string
Example:
#include<stdio.h>
#include<string.h>
main()
{
char str1[20];
char str2[20];
Bhavya P S.,Asst prof.,KVGCE Page 6
Module 4
printf(“enter string2”);
gets(str2);
strcpy(str1,str2);
printf(“after copying string 1 is\n”);
puts(str1);
}
Output:
Enter string2
Hello
After copying string1 is
Hello
strcmp():
This function is used to compare two strings and check whether those two strings are equal or
not.
Syntax: strcmp(str1,str2):
It returns 3 values.
It will return 0, if both the strings are equal.
It will return -1, if str1<str2.
It will return +1, if str1>str2.
Example:
#include<stdio.h>
#include<string.h>
main()
{
char str1[20];
char str2[20];
printf(“enter string1\n”);
gets(str1);
printf(“enter string2\n”);
gets(str2);
k=strcmp(str1, str2);
if(k==0)
{
printf(“string 1 is equal to string 2\n”);
}
else if(k==+1)
Bhavya P S.,Asst prof.,KVGCE Page 7
Module 4
{
printf(“string 1 is greater than string 2\n”);
}
else
{
printf(“string 1 is lesser than string 2\n”);
}
}
Output:
enter string1
abc
enter string2
abd
string 1 is lesser than string 2
strcat():
This string function is used to join two strings.
Syntax: strcat(str1,str2);
Example:
#include<stdio.h>
#include<string.h>
main()
{
char str1[20];
char str2[20];
printf(“enter string1\n”);
gets(str1);
printf(“enter string2\n”);
gets(str2);
strcat(str1,str2);
printf(“after concatenation\n”);
puts(str1);
}
Output:
enter string1
hello
Bhavya P S.,Asst prof.,KVGCE Page 8
Module 4
enter string2
sullia
after concatenation
hellosullia
strupr():
This string function is used to convert lower case into upper case.
Syntax: strupr(str);
Example:
#include<stdio.h>
#include<string.h>
main()
{
char str[20];
printf(“enter the name\n”);
gets(str);
strupr(str);
printf(“uppercase is \n”);
puts(str);
}
Output:
enter name
hello
uppercase is
HELLO
strlwr():
This string function is used to convert upper case into lower case.
Syntax: strlwr(str);
Example:
#include<stdio.h>
#include<string.h>
main()
{
char str[20];
Bhavya P S.,Asst prof.,KVGCE Page 9
Module 4
printf(“enter the name\n”);
gets(str);
strlwr(str);
printf(“lowercase is \n”);
puts(str);
}
Output:
enter name
HELLO
lowercase is
hello
strrev():
This string function is used to reverse a string.
Syntax: strrev(str);
Example:
#include<stdio.h>
#include<string.h>
main()
{
char str[20];
printf(“enter the name\n”);
gets(str);
strrev(str);
printf(“reversed string is \n”);
puts(str);
}
Output:
enter name
hello
uppercase is
olleh
ARRAY OF STRINGS[multidimensional strings]:
It is an array of 1D character array which consists of strings as its individual elements.
Syntax: char name[size1][size2];
Bhavya P S.,Asst prof.,KVGCE Page 10
Module 4
Ex: char days[7][10] = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”,
“Saturday”};
Programs without using string manipulating functions:
1. C code to find Length of the string without using strlen() function.
#include <stdio.h>
int main()
{
char str[100];
int i,length=0;
printf("Enter a string: \n");
scanf("%s",str);
for(i=0; str[i]!='\0'; i++)
{
length++;
}
printf("\nLength of input string: %d",length);
return 0;
}
2. C code to compare two strings without using strcmp() function
#include <stdio.h>
int compare(char a[],char b[]);
int main()
{
char str1[20];
char str2[20];
int k;
printf("Enter the first string : ");
gets(str1);
printf("Enter the second string : ");
gets(str2);
k= compare(str1,str2); // calling compare() function
if(k==0)
printf("strings are same");
Bhavya P S.,Asst prof.,KVGCE Page 11
Module 4
else
printf("strings are not same");
return 0;
}
int compare(char a[], char b[])
{
int flag=0,i;
for(i=0;a[i]!='\0'&& b[i]!='\0';i++)
{
if(a[i]!=b[i])
{
flag=1;
break;
}
}
if(flag==0)
return 0;
else
return 1;
3. C code to concatenate two strings without using strcat() function
#include<stdio.h>
void main()
{
char str1[25],str2[25]; int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
Bhavya P S.,Asst prof.,KVGCE Page 12
Module 4
printf("\nConcatenated String is %s",str1);
}
Pointers
Pointers :
A pointer is a variable which stores the address of another variable.
Declaring pointer variable:
Syntax:
data_type *ptrname;
Where,
data_type - It specifies the type of pointer variable that you want to declare int, float, char
and double etc.
*(Asterisk) – It is refereed as indirection operator or dereference operator used to declare
a pointer.
ptrname - Specifies the name of the pointer variable.
Example:
int *p //Declares a pointer variable p of integer type.
float *p //Declares a pointer variable p of float type.
Initialization of pointer variable:
The process of assigning address of a variable to a pointer variable is known as Initialization.
Syntax:
data_type *ptrname = &expression
Where,
data_type - It can be any basic datatype.
ptrname - It is pointer variable
expression - It can be constant value or any variable containing value.
Ex:
int a=10;
int *p; // pointer decalration
*p = &a; // pointer initilaization
Bhavya P S.,Asst prof.,KVGCE Page 13
Module 4
a p
10 2000
Address=2000 Address=4000
Write a C program to find sum of two numbers using pointers .
#include <stdio.h>
int main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of the numbers = %d\n", sum);
return 0;
}
Passing arguments to functions using pointers:
#include<stdio.h>
int add(int *a,int* b); //function declaration
void main()
{
int sum,x,y;
printf("\n Enter Any Two Numbers To Add : ");
scanf("%d%d",&x,&y);
sum=add(&x,&y); //calling the function
printf("\n Addition = %d",sum);
}
int add(int *a, int * b) //definition of function
{
Bhavya P S.,Asst prof.,KVGCE Page 14
Module 4
int c;
c=*a+*b;
return c;
}
Null pointer:
We can initialize pointer variable to NULL or Zero.
int *p = NULL;
Pointer to pointer:
Pointer pointing to another pointer is called pointer to pointer.
Syntax:
datatype **ptr_name;
Example :
int a=10;
int *p;
int **pp;
p=&a;
pp=&p;
Generic pointers
• A generic pointer is a pointer variable that has void as its data type.
• The void pointer or generic pointer is a special type of pointer that can be used to point to
variables of any data type.
• It is declared using void keyword.
Eg:
void *ptr;
Example:
#include <stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *(int*)ptr);
return 0;
}
Pointer arithmetic:
Bhavya P S.,Asst prof.,KVGCE Page 15
Module 4
1. Pointers can be incremented
include <stdio.h>
int main()
{
int a = 22;
int *p = &a;
p++;
}
2. Pointer can be decremented
include <stdio.h>
int main()
{
int a = 22;
int *p = &a;
p--;
}
1. We can add a value to the pointer variable
include <stdio.h>
int main()
{
int a = 22;
int *p = &a;
p=p+3;
}
4. We can subtract a value from the pointer variable
include <stdio.h>
int main()
{
int a = 22;
int *p = &a;
p=p-3;
}
Develop a program using pointers to compute the sum, mean and standard deviation of all
elements stored in an array of n real numbers(pointer and array concept).
#include <stdio.h>
#include <math.h>
Bhavya P S.,Asst prof.,KVGCE Page 16
Module 4
int main()
int i, n;
float a[10], sum = 0, mean, std, sumstd=0, *ptr;
printf("Enter total number of elements: ");
scanf("%d", &n);
printf("Enter the value of elements: \n");
for (i = 0; i < n; i++ )
scanf("%f", &a[i]);
ptr=a;
for (i = 0; i < n; i++)
sum =sum+*ptr;
ptr++;
mean = sum / n;
ptr=a;
for (i = 0; i < n; i++)
sumstd += (ptr - mean) * (ptr - mean);
ptr++;
std = sqrt(sumstd / n);
printf(“sum %f \n", sum);
printf("Mean: %f \n", mean);
Bhavya P S.,Asst prof.,KVGCE Page 17
Module 4
printf("Standard Deviation: %f", std);
return 0;
Bhavya P S.,Asst prof.,KVGCE Page 18