Strings PART1
Strings PART1
Strings
Enter a string:
Lovely Professional University
Output
String is:
Lovely Professional University
©LPU CSE101 C Programming
Drawback of gets():
gets() has been removed from c11. So it might give you a
warning when implemented.
We see here that it doesn’t bother about the size of the array.
So, there is a chance of Buffer Overflow.
Alternative of gets():
To overcome the above limitation, we can use fgets as :
Syntax : char *fgets(char *str, int size, FILE *stream)
Example : fgets(str, 20, stdin); as here, 20 is MAX_LIMIT
according to declaration.
#include <stdio.h>
#define MAX_LIMIT 20
int main()
{
char str[MAX_LIMIT];
fgets(str, MAX_LIMIT, stdin);
printf("%s", str);
return 0;
}
Hello
Output
#include<stdio.h>
int main()
{
char str1[20],str2[10];
int x;
printf("\n Enter first string:");
gets(str1);
printf("\n Enter second string:");
gets(str2);
x=stricmp(str1,str2);
if(x==0)
{
printf("\n Strings are equal");
}
else if(x>0)
{
printf("\n First string is greater than second string(strings are not equal)");
}
else
{
printf("\n First string is less than second string(strings are not equal)");
}
return 0;
}
//consider str1(HELLO) and str2(hello) and if we apply stricmp on these strings, then 0 will be returned, as
strings are equal
str1[i]=str1[i]-32;
}
puts("string in upper is");
puts(str1);
return 0;
}
char x[100];
int i=0,count=0;
printf("\n Enter the string:");
gets(x);
while(x[i]!='\0')
{
if(x[i]=='a'||x[i]=='e'||x[i]=='i'||x[i]=='o'||x[i]=='u'||x[i]=='A'||x[i]=='E'||x[i]=='I'||
x[i]=='O'||x[i]=='U')
{
count++;
}
i++;
}
printf("\n Number of vowels in the string are:%d",count);
return 0;
}
#include<stdio.h>
int main()
{
char *g="C Programming";
int length=0,i=0;
while(*g!='\0')
{
printf("%c",*g);//Value at address
g++;//Pointer is incremented by 1 after each iteration
length++;//Variable for counting length
}
printf("\nLength of the string is:%d",length);
return 0;
}
#include<stdio.h>
int main()
{
char x[100];
int i=0,length=0,c=0,w=1;
printf("\n Enter String:");
gets(x);
while(x[i]!='\0')
{
if(x[i]==' ' && x[i+1]!=' ')
{
w++;
}
c++;
i++;
}
printf("\n Total number of characters are:%d, and no. of words are:%d",c,w);
return 0;
}
#include <stdio.h>
int main()
{
char name[]="Hello World"; //string char array
int i=0;
while(name[i]!='\0') //untill null character
{
printf("%c\n", name[i]);
i++;
}//end while
}//
#include<stdio.h>
int main()
{
char str1[]="Good";
char *str2;
str2=str1;
puts(str2);
return 0;
}
A. Good
B. Garbage value
C. Compile time error
D. Nothing will be visible
#include<stdio.h>
int main()
printf(8+"C Programming\n");
return 0;
A. mming
B. ming
C. amming
D. gramming
Output-11 ??
#include <stdio.h>
int main()
return 0;
A. 72 W
B. H W
C. W H
D. Compile-time error
Output-13??
#include <stdio.h>
int main()
{
char *str="WORLD";
while(*++str)
{
printf("%c",*str);
}
return 0;
}
A. ORLD
B. WORLD
C. RLD
D. Compile time error