Strings 7
Strings 7
Strings 7
Introduction:
Consider the statement printf(“HELLOW”); the printf() statement displays the message
“HELLOW” on the screen. Let us knoww understand how the message “HELLOW” is
stored in memory and how th printf() works().
The message “HELLOW” is stored in memory as
H E L L O W \0
Note that the last location in the memory block has the special character ‘\0’ is
automatically appended to the end of the messageby the compiler.
DEFNITION:
A String in C is defined as sequence of charecters terminated by a special character
‘\0’ is called null character.
Declaration of Array of char type:
A String variable is a valid C variable name and is always declared an array.
Syntax:
char string_name[size];
the size determines the number of charecters in the string name.
Example:
An array of char typen ot store the above string is to be declared as follows: char
str[7]=”HELLOW”;
H E L L O W \0
Str[0] Str[1] Str[2] Str[3] Str[4] Str[5] Str[6]
OUTPUT:
Enter any string
HI
U entered is
Hi
getchar() and putchar():
getchar() is used to read a character from keyboard
syntax:
ch=getchar();
putchar() is used to print a character to the output screen
syntax:
putchat(ch);
where ch represents a variable of type char or a character constant.
example:
#include<stdio.h>
#include<conio.h>
void main()
{
char a;
clrscr();
printf(“enter a character”);
a=getchar(); /* reading the charecter */
printf(“u entered is\n”);
putchar(a); /*printing the charecter*/
getch();
}
Output:
Enetr a character
H
U entered is H
Example2:
/* accept a line of charecters and display using getchar() & putchar() functions*/
#include<stdio.h>
#include<conio.h>
void main()
{
char str[100],ch;
int I=0;
printf(“enter a line of charecters\n”);
ch=getchar();
while(ch != ‘\n’) /*reading and storing*/
{
str[i]=ch;
ch=getchar();
i++:
}
str[i]=’\0’;
printf(“the line of chrecters u entered is\n”); for(i=0;str[i]!=’\0’;i+
+) /*
displaying*/
{
putchar(str[i]);
}
getch();
}
OUTPUT:
enter a line of charecters
HOW R U..?
the line of chrecters u entered is
HOW R U..?
gets() and puts():
gets() is used to accept a string upto newline character. It automatically appends the null
character’\0’ to the end of the string.
Syntax:
gets(str);
the purpose of puts() is to display a string contained in a string variable. It automatically
appends the new line character’\n’ to the end of the string.as a result the cursor is moved
down by 1 line afer the string is displayed.
Expand the data
###############
Syntax:
puts(str);
exxample:
#include<stdio.h>
#include<conio.h>
Void main()
{
char str[100];
printf(“enter a line of charecters\n”);
gets(str); /*reading*/
printf(“the line of chrecters u entered is\n”);
puts(str); /*
displaying*/ getch();
}
###############################
STRING MANIPULATIONS
Expand the data
####################
C supports large set of string handling functions, which are contained in the header file
#include< sting.h>
The most commonly performed operations ver strings are:
1. finding the length of the string (strlen())
2. coping one string to another string (strcpy())
3. comparing twostrings (strcmp())
4. concatenation oftwo strings (strcat())
Finding the length of the string:
The function strlen() return the number of characters in the given string excluding null
character (‘\0’).
Syntax:
strlen(str);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
char str[30]=”hellow”;
int k;
clrscr();
k=strlen(str);
printf(“the length of the string is %d”,k);
getch();
}
OUTPUT:
The length of the string is 6.
Description:
Here, the string ”hellow” stored in memory as follows
H E L L O W \0
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20]="hello",str2[30],str3[20];
clrscr();
strcpy(str2,str1); /* copying from str1 to str2 */
printf("the string in str2 is %s\n",str2);
strcpy(str3,"hi"); /* copying a constant “hi” to str3*/
printf("the string in str3 is %s",str3);
getch();
}
OUTPUT:
The string in str 2 is hello
The string in str3 is hi
Comparing two strings :
strcmp() is used to compare two strings
syntax:
strcmp(str1,str2);
description:
str1 and str2 represent two strings compared. Str1 str2 can be string constants or
string variables.thefunction returns the numerical difference between the first non-
matching pair of charactres of str1 and str2. It returns a positive value when str1 ig
alphabetically greater than str2.
It returns a negative value when str1 ig alphabetically lower than str2.it returns zero
when str1 and str2 are equal.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20]="hello",str2[30]="hello";
int i;
clrscr();
i=strcmp(str2,str1); /* comparing str1 and str2 */
printf("comparision of str1 and str2 is %d",i);
getch();
}
OUTPUT:
comparision of str1 and str2 is 0
Example:
char str1[20]="xyz",str2[30]="xxz";
int i;
i=strcmp(str2,str1);
OUTPUT:
comparision of str1 and str2 is 1
Example:
char str1[20]="xxz",str2[30]="xyz";
int i;
i=strcmp(str2,str1);
OUTPUT:
comparision of str1 and str2 is -1.
Concatenation oftwo strings :
The built-in functionto perform concatenation of two strings is strcat()
syntax:
strcat(str1,str2);
it appends both str2 to str1. Str2 can be a string variable or a string constant.but str1
should be a string variableand the size of str1 should be large enough to collect even str2
also inaddition to its own string.
Expand the data
############
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20]="hello",str2[10]="hi";
clrscr();
strcat(str1,str2);
printf(“after concatenating str1 contains %s”,str1);
getch();
}
Output:
After concatenating str1 contains hellohi
Malloc():- <alloc.h>
It is a function which is used to allocating memory at run time.
Syntax:- void *malloc(size_t size);
size_t:- unsigned integer. this is used for memory object sizes.
Calloc():- <alloc.h>
This is also used for allocating memory at run time.
Syntax: void *calloc(size_t nitems, size_t size);
Program:Write a program to create a dynamic array (vector) store values from keyboard
display
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
void main()
{
int *a,n,i;
clrscr();
printf("Enter no of elements:");
scanf("%d",&n);
a=(int *)malloc(n* sizeof(int));
//a=(int *)calloc(n,sizeof(int));
printf("Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",a+i);
}
printf("Given array elements:");
for(i=0;i<n;i++)
{
printf("%d\t",*(a+i));
}
getch();
}
Program: Write a program to create a dynamic memory allocation for two dimensional
array and read values from keyboard and display
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
void main()
{
int **a,r,c,i,j;
clrscr();
printf("Enter no of rows and columns:");
scanf("%d%d",&r,&c);
a=(int **)malloc(r* sizeof(int *));
//a=(int *)calloc(n,sizeof(int));
for(i=0;i<r;i++)
{
*(a+i)=(int *)malloc(c*sizeof(int));
}
printf("enter array elements:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",*(a+i)+j);
}
}
printf("Given array elements:");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%3d\t",*(*(a+i)+j));
}
printf("\n");
}
free(a);
getch();
}
for(step=0;step<n-1;++step)
for(i=0;i<n-step;++i)
{
if(*(num+i)>*(num+i+1))
{
temp=*(num+i);
*(num+i)=*(num+i+1);
*(num+i+1)=temp;
}
}
printf("In ascending order:\n"); for(i=0;i<n;+
+i)
printf("%d \t",*(num+i));
return 0;
}
Command-line arguments
The C language provides a method to pass parameters to the main() function. This is
typically accomplished by specifying arguments on the operating system command line
(console).
The prototype for main() looks like:
int main(int argc, char *argv[])
{
…
}
There are two parameters passed to main(). The first parameter is the number of items on
the command line (int argc). Each argument on the command line is separated by one or
more spaces, and the operating system places each argument directly into its own null-
terminated string. The second parameter passed to main() is an array of pointers to the
character strings containing each argument (char *argv[]).
For example, at the command
prompt: test_prog 1 apple
orange 4096.0
There are 5 items on the command line, so the operating system will set argc=5 . The
parameter argv is a pointer to an array of pointers to strings of characters, such that:
argv[0] is a pointer to the string “test_prog”
argv[1] is a pointer to the string “1”
argv[2] is a pointer to the string “apple”
argv[3] is a pointer to the string “orange”
argv[4] is a pointer to the string “4096.0”
Example program for Command line arguments
1. #include <stdio.h>
2.
3. int main(int argc, char *argv[])
4. { if ( argc != 3) {
5. printf("Usage:\n %s Integer1 Integer2\n",argv[0]);
6. }
7. else {
8. printf("%s + %s = %d\n",argv[1],argv[2], atoi(argv[1])+atoi(argv[2]));
9. }
10. return 0;
11. }
Explanation
line 4 : we check if the user passed two arguments to the program. We actually need two
arguments but in C the first argument ( argv[0] ) is the name of our program, so we need
two more.
line 5 : If the user didn't pass two arguments we print the usage of our program and exit
line 8 : Using atoi() function we convert pointers to char (string) to decimal numbers and
display their sum.
C program prints the number and all arguments which are passed to it.
#include <stdio.h>
void main(int argc, char *argv[])
{
int c;
printf("Number of command line arguments passed: %d\n", argc);
}
/*program to find large and small from an array using a function*/
#include<stdio.h>
find(x,m,l,s)
int x[];
int m;
int *l,*s;
{
int i;
*l=*s=x[0];
for(i=1;i<m;i++)
{
if (x[i]>*l)
*l=x[i];
if (x[i]<*s)
*s=x[i];
}
}
main()
{
int a[10],n,i,lar,sma;
clrscr();
printf("enter n");
scanf("%d",&n);
printf("enter array elements\n"); for(i=0;i<n;i+
+)
scanf("%d",&a[i]);
find(a,n,&lar,&sma);
printf("largest=%d smallest=%d\n",lar,sma);
getch();
}
#include<stdio.h>
void find(str,nw,nc,nv)
char str[];
int *nw,*nc,*nv;
{
int i=0;
*nw=0;
*nc=0;
*nv=0;
while (str[i]!='\0')
{
putchar(str[i]);
if (str[i]==' ')
(*nw)++;
else
if ((str[i]=='a')||(str[i]=='e')||(str[i]=='i')
||(str[i]=='o')||(str[i]=='u'))
(*nv)++;
else
(*nc)++;
i++;
}
(*nw)++;
}
main()
{
char
line[80],ch; int
i,n,nw,nc,nv;
clrscr();
printf("enter a line of text\n");
i=0;
do
{
ch=getchar();
line[i]=ch; i+
+;
} while(ch!='\n');
i--;
line[i]='\0';
printf("the line of text = %s\n",line);
find(line,&nw,&nc,&nv);
printf("The number of words = %d\n",nw);
printf("The number of characters = %d\n",nc);
printf("The number of vowels = %d\n",nv);
getch();
/*--------------------------------------------------------
program to access elements of a single dimensional array
using a pointer variable
-------------------------------------------------------*/
#include<stdio.h>
#include<conio.h>
main()
{
static int a[5] = { 1,2,3,4,5 };
int i,*p;
clrscr();
/*--------------------------------------------------------
program to access elements of a single dimensional array
using a pointer variable
/*-------------------------------------------------------
program to find largest and second largest from an array
using pointer variables
--------------------------------------------------------*/
#include<stdio.h>
#include<conio.h>
void findlsl(x,n,l,sl)
int *x,n,*l,*sl;
{
int i;
*l = 0;
*sl = 0;
for(i=0;i<n;i++)
{
if ( *(x+i) > *l)
{
*sl = *l;
*l = *(x+i);
}
else
if ( *(x+i) > *sl )
*sl = *(x+i);
}
}
main()
/*-------------------------------------------------------
program to find length of a string
---------------------------------------------------------*/
#include<stdio.h>
#include<conio.h>
main()
{
char *name;
char *p;
int n;
clrscr();
name="VARMA";
p=name;
while( *p !='\0')
{
printf("%c is stored at position%u\n",*p,p);
p++;
}
n=p-name;
printf("the length of the string is %d\n",n);
getch();
}
/*--------------------------------------------------------
program to find sum of elements of a given array
using a pointer variable
--------------------------------------------------------*/
#include<stdio.h>
#include<conio.h>
addition(x,n,s)
main()
{
static int a[5]={10,20,30,40,50};
int sum=0;
clrscr();
addition(a,5,&sum);
printf("the sum = %d\n",sum);
getch();
}
/*--------------------------------------------------------
program to find no of vowels in a line of text
using a pointer variable
--------------------------------------------------------*/
#include<stdio.h>
#include<conio.h>
countvowels(str,n,nv)
char *str;
int n,*nv;
{
int i;
i=0;
while( *str!='\0')
{
if((*str=='a')||(*str=='e')||(*str=='i')||(*str=='o')||(*str=='u')) (*nv)+
+;
str++;
}
}
main()
{
char ch,line[80];
int i,nv;
clrscr();
printf("enter a line of text\n");
i=0;
/*-----------------------------------------------------------
program to find no of tabs,
number of lines, uppercase characters,
lowercase characters and blank spaces in a
file
-----------------------------------------------------------*/
#include<stdio.h>
#include<conio.h>
count(str,nol,nouc,nolc,nobl,notb)
char *str;
int *nol,*nouc,*nolc,*nobl,*notb;
{
while( *str!='\0')
{
if(*str>64 && *str<91) (*nouc)
++;
else
if(*str>96 && *str< 123) (*nolc)
++;
else
if(*str==' ')
(*nobl)++;
else if(*str=='\
n')
(*nol)++;
else
if(*str=='\t')
(*notb)++;
str++;
}
Department of BS&H Page 146
NRI Institute of Technology, Pothavarappadu
}
main()
{
char str[80];
char ch;
int i,nol,nouc,nolc,nobl,notb;
clrscr();
printf("enter text\n");
i=0;
do
{
ch=getchar();
str[i]=ch; i+
+;
}while(ch!=EOF);
i--;
str[i]='\0';
printf("line of text=\n");
printf("%s\n",str);
nol=nouc=nolc=nobl=notb=0;
count(str,&nol,&nouc,&nolc,&nobl,¬b);
printf("no of lines = %d\n",nol);
printf("no of upper case characters = %d\n",nouc);
printf("no of lower case characters = %d\n",nolc);
printf("no of blank characters = %d\n",nobl);
printf("no of tabs = %d\n",notb);
getch();
}
/*---------------------------------------------
program to pass an array to a function
sequential search using pointers
---------------------------------------------*/
#include <stdio.h>
#include<conio.h>
void sequentialsearch(b,m,t,found,pos)
int b[];
int m,t;
int *found,*pos;
{
int i=0;
while(i<m)
{
if ( b[i] == t)
{
main()
{
int n,a[10],i,tar,found,pos;
clrscr();
printf("enter n");
scanf("%d",&n);
printf("enter array elements \n"); for(i=0;i<n;i+
+)
scanf("%d",&a[i]);
/*---------------------------------------------
program to pass an array to a
function binary search
--------------------------------------------*/
#include <stdio.h>
#include<conio.h>
void binsearch(b,m,t,found,pos)
int b[];
int m,t;
int *found,*pos;
{
int low,high,mid;
low=0;
high=m-1;
s
t
;
c
l
r
s
c
r
(
)
;
printf("enter stno name, m1,m2 m3"); scanf("%d%s%d%d
%d",&st.stno,st.stname, &st.m1,&st.m2,&st.m3);
process(&st);
********
Summary
###############
Review Questions
###############
Multiple Choice Questions
####################