String Full
String Full
Programming
Strings
Strings in C
● String literals or string constant is a sequence of characters enclosed within
double quotes
● Example : “Hello Everyone”
Storing String Literals
● String literals are stored as an array of characters
● It's always ended with null character, automatically added by the compiler
● If you want to print just a part of the string “%.ns” can be used
where n is the number of characters to be displayed on the screen.
Writing String Using Printf
● If you want to print part of string within specified field then
“%m.ns” where m represents the size of the field within which
the string will be displayed
● m is useful for right justify the string
Writing String Using Puts
● puts() function is a function declared in <stdio.h> library and is
used to write strings to output screen
● Puts() function automatically writes a newline character after
writing the string to the output screen
Reading String Using Scanf
● Both gets() and scanf() functions have no way to detect when the character
array is full
● Both of them never checks the maximum limit of the input characters.
Hence they may cause undefined behaviour
● scanf() has the way to set the limit for the number of characters to be
stored in the character array
● By using %ns, where n indicates the number of characters allowed to store
in the array
Reading String Using Gets and Scanf
Reading String Using Gets and Scanf
#include <stdio.h>
int main()
{
int character;
character = getchar();
● int main() {
● char s1[] = "Hello world!";
●
● // Ensure destination has enough space
● char s2[50];
● printf("%s", s2);
● return 0;
● }
Putchar() Function
● The putchar function is used in the standard C library to write out a character
given to it as an argument to the standard output.
● putchar() function does not take any parameters
● Putchar () function returns an integer. It accepts and integer argument.
● Character is internally represented as binary format only. There is no difference in
writing int ch and char ch.
● Example A. Decimal equivalent of A in ASCII is 65. If we store character in a
character variable then binary equivalent is stored.
● The binary form getting from integer and from character are same
Strcpy() Function
● Strcat() function appends the content of string str2 at the end of the string str1
● Strcat () function automatically adds NULL character at the end of the
resultant string
Strcmp() Function
● Greater than Zero ( > 0 ): Returns a value greater than zero is returned when the first not-
matching character in s1 has a greater ASCII value than the corresponding character in s2.
● Lesser than Zero ( < 0 ): Returns a value less than zero is returned when the first not-matching
character in s1 has a lesser ASCII value than the corresponding character in s2.
Table of Contents
Strings in C