Beruflich Dokumente
Kultur Dokumente
Strings
By
Prithiviraj.M
COMP102 Prog. Fundamentals: Strings / Slide 2
Character Strings
A sequence of characters is often referred to as a
character string.
A string is stored in an array of type char ending with
the null character '\0 '.
COMP102 Prog. Fundamentals: Strings / Slide 3
Character Strings
COMP102 Prog. Fundamentals: Strings / Slide 5
String Literals
strlen
strlen returns the length of a NULL terminated character string:
size_t strlen (char * str) ;
Defined in string.h
size_t
A type defined in string.h that is equivalent to an unsigned int
char *str
Points to a series of characters or is a character array ending with '\0'
The following code has a problem!
char a[5]={a, b, c, d, e};
strlen(a);
COMP102 Prog. Fundamentals: Strings / Slide 10
strcpy
Copying a string comes in the form:
char *strcpy (char * destination, char * source);
A copy of source is made at destination
source should be NULL terminated
destination should have enough room
(its length should be at least the size of
source)
The return value also points at the
destination.
COMP102 Prog. Fundamentals: Strings / Slide 11
main( )
{
char name[ ] = vishishth" ;
int i = 0 ;
while ( i <= 8 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
COMP102 Prog. Fundamentals: Strings / Slide 12
Pointer program
main( )
{
char name[ ] = vishishth" ;
char *ptr ;
ptr = name ; /* store base address of string */
while ( *ptr != `\0' )
{
printf ( "%c", *ptr ) ; ptr++ ;
}
}