MEJ-C Language 8
MEJ-C Language 8
Writing strings:
printf(“%s”, name);
Formatted printing
%10s, %-10s, %10.4s, %*.*s, %*.3s, %10.*s
printf(“%*.*s”, i, j, name);
/*P1 Reading a line of text */
line
#include <stdio.h> a b c d \n
#include <conio.h>
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
#include <ctype.h>
main()
{ char line[10], ch ; ch i
int i = 0; a 01
--
printf("Enter the text, press ENTER key at the end : \n"); ab cd\n
do
{ ch = getchar();
line[i] = ch; /* line[i++] = ch; not [++i] */
i++;
} while(ch != '\n');
line[i-1] = '\0'; To read/ write individual character
printf("\n%s", line); • getchar(); • gets(name);
getch(); • putchar(ch); • puts(name);
}
Declaration, initialization, reading and writing
char x1[ ] = "Hello“;
char x2[ ] = {'B','y','e','\0'};
char x3[ ] = "Thank You";
char x4[20], x5[20];
scanf("%s", x4);
gets(x5);
printf("%s %10s %-10s %10.5s", x1, x2, x3, x4);
puts(w5);
Length of a string
str1
All strings are terminated in NULL. This feature can
‘a’ ‘b’ ‘c’ ‘d’ ‘e’ ‘\0’
be used to manipulate strings
[0] [1] [2] 3] [4] [5]
For finding out length of a string → use a for loop
and keep on incrementing a counter till \0 is reached.
/* P2 Length of string */
#include <stdio.h>
#include <conio.h>
main()
{ char str[20];
int i;
printf("Enter the string - one word: ");
scanf("%s", str);
for (i=0; str[i] != '\0'; i++);
printf("\nNo. of characters in '%s' is %d", str, i);
getch();
}
Copy a string s1
= cannot be used for copying a string ‘a’ ‘b’ ‘c’ ‘\0’
S1[0] s1[1] S1[2] s1[3]
Copy character by character till the null character
and assign a NULL as the last character of new string. s2
Q1. Write a program to read a line of text, generate a new string by removing all vowels
from the string. Print both strings
Q2. Write a program to read string containing number of words, print it one word per line.