Académique Documents
Professionnel Documents
Culture Documents
STRINGS
A string is a collection of characters terminated by a null
character ‘\0’.
The strings are always enclosed in double quotes (“ “) and may include
letters, numbers, escape sequences, blank space and some special
characters.
Some valid strings are
“Good Morning”
“Welcome to the world of programming”
“Address=142,Lawrence Road,Jalandhar”
“123-456-789”
Defining String Variables
Just like array of integers or any other data type, the string variables
which are array of characters can be defined using the following syntax:
char string_variable[size];
The string_variable is actually the name of the array and size represents
the maximum number of characters that can stored and it must be a
positive integer value.
For example: character Name of Size
data type array of character specification
In the first method of initialization, the compiler allocates space for 7 characters for array
name. The first six characters are filled with ‘P’,’A’,’N’,’K’,’A’,’J’ characters and end with character
‘\0’ (null character) automatically.
For example: The statement
char name[10]=“PANKAJ”;
In the above initialization, the compiler allocates space for 10 characters, where
first 7 characters are fill with ‘P’,’A’,’N’,’K’,’A’,’J’ and ends with ‘\0’. The remaining 3
spaces of the character array are filled with null characters(‘\0’) automatically. This
method of initialization results in wastage of memory.
P A N K A J \0 \0 \0 \0
A better method of initialization is to omit the size of the character array at the
time of its initialization. In such case, compiler automatically computes the size.
strings. Using these operations, the strings can be compared, copied and
int strlen() – This function returns the number of characters in a string, not
H e l l o \0
H e l l o E v e r y b o d y \0
To copy a string to another using strcpy() function
#include<stdio.h>
#include<string.h>
main() Output:
{ Enter a string:
char a[80],n[80]; Programming
printf(“\n Enter a string:”); String after copying
gets(a); Programming
strcpy(n,a);
printf(“\nString after copying:”);
puts(a);
}
char strcat(s1,s2): This function accepting two strings as arguments,
concatenates the second string to the first string. The syntax is
strcat(string1, string2);
strcat(“through”, ”put”);
strrev()
To reverse a given string using library function strrev()
#include<stdio.h>
#include<string.h>
main() Output
{ Enter a string: Hi Hello
char a[80]; String before reversed:
printf(“\n Enter a string:”); Hi Hello
gets(a); String after reversing
printf(“\n String before reversed:%s”,a); olleH iH
printf(“\n String after reversing:%s”, strrev(a));
}
strcmp
• strcmp(stringa, stringb)