STRINGS
STRINGS
C LANGUAGE LAB
DEFINITION OF STRING
#include<stdio.h>
#include<conio.h>
void main(){
clrscr();
char name[20];
printf(“Enter your name: ”);
scanf(“%s”, &name);
printf(“Your name is %s ”,name);
getch();
}
Example 2: Using getchar() to read a
line of text
#include<stdio.h>
#include<conio.h>
void main(){
char name[30], ch;
int i = 0;
printf(“Enter your name: “);
while(ch != ‘\n’){
ch = getchar();
name[i] = ch;
i++;
}
name[i] = ‘\0’;
printf(“Your name is %s”,name);
getch();
}
Example 3: Using standard library
function to read a line of text
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main(){
clrscr();
char name[30];
printf(“Enter a name: ”);
gets(name);
printf(“Name: ”);
puts(name);
getch();
}
STRING FUNCTIONS
#include<stdio.h>
#include<conio,h>
#include<string.h>
void main()
{
char str1[] = "This is ", str2[] = "programiz.com";
strcat(str1,str2);
puts(str1);
puts(str2);
getch();
}
Example strcmp()
#include<stdio.h>
#include<conio,h>
#include<string.h>
void main()
{
char str1[] = “abcd”;
char str2[] = “abbd”;
char str3[] = “abcd”;
int result;
result = strcmp(str1, str2);
printf(“str1 compare str2 result is %d \n”,result);
result = strcmp(str1, str3);
printf(“str1 compare str3 result is %d \n”,result);
getch();
}