PL1 Lecture 9 String
PL1 Lecture 9 String
List of topics,
The concept of string
Examples of string
String Functions
The concept of STRING
#include <stdio.h>
int main ()
{
char string[20] = "this is a
string";
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "
C course" ;
char target[ ]= "
C tutorial" ;
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " C course" ;
char target[ ]= "C tutorial" ;
}
STRCPY()
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " C Programming" ;
char target[20]= "Hello" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strcpy ( target, source ) ;
printf ( "\ntarget string after strcpy( ) = %s", Source string = C Programming
target ) ; return 0; Target string = Hello
}
Target string after strcpy( ) = C Programming
STRNCPY()
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "Programming" ;
char target[20]= "Hello" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strncpy ( target, source, 3) ; source string = Programming
printf ( "\ntarget string after strncpy( ) = %s", target string = Hello
target ) ; return 0; target string after strncpy( ) = Prolo
}
STRLEN()
#include
<stdio.h>
#include
<string.h>
int main( )
{
int len;
char
array[20]=”
printf
C ( "\string length = %d \n" , String length = 13
len );
Programming"
} return
; 0;
len =
strlen(array) ;
STRCMP()
•strcmp( ) function in C compares two given strings and returns zero if they are same.
•If length of string1 < string2, it returns < 0 value. If length of string1 > string2,
it returns > 0 value. Syntax for strcmp( ) function is given below.
STRCMP()
#include
<stdio.h>
#include
<string.h> int
main( )
{
char str1[ ] =
”This" ;
char str2[ ] =
”is C
Programming
" ; Output:
int i, j, k ; 0
i = strcmp -1
( str1, 1
”This" ) ;
j = strcmp
( str1, str2 ) ;
k = strcmp
( str1, ”T" ) ;
STRNCMP()
#include <stdio.h>
#include <string.h>
int main( )
{
char str1[ ] = "This is a Program";
char str2[ ] = "This is C
Programming";
int i, j;
i = strncmp ( str1, str2, 9) ;
j = strncmp ( str1, str2, 8 ) ;
Output:
printf ( "\n%d %d", i, j) ; 1
return 0; 0
}