Lec 15 PDF
Lec 15 PDF
<string.h>
Function Purpose
strlen Returns the number of characters in a string
strcpy Makes a copy of a string
strncpy Makes a copy of a string
strcat Appends a string to the end of another string
Lecture 15 strncat
strcmp
Appends a string to the end of another string
Compare two strings alphabetically
Strings
strncmp Compare two strings alphabetically
CSE115: Programming Language I
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
dest dest
t e s t s t r i n g \0
• If source string is longer than the destination string, the • If source string is longer than the destination string, the
overflow characters are discarded automatically. overflow characters are discarded automatically.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
dest dest
t e s t s
Function strncpy strcpy and strncpy example
#include <stdio.h>
• Function strncpy copies source string into the #include <string.h>
destination string by specifying the number of characters int main( )
to copy. {
char source[ ] = "fresh2refresh";
char dest[15]; char target[20]= "";
printf("source = %s\n", source);
strncpy(dest, “test string”, 6); printf("target = %s\n", target);
strcpy(target, source);
dest[6] = ‘\0’; printf("target after 1st strcpy( ) = %s\n", target);
strcpy(target, "***************");
• You have to place the null character manually. printf("target after 2st strcpy( ) = %s\n", target);
• If source string is longer than the destination string, the strncpy(target, source, 6);
printf("target after strncpy( ) = %s\n", target);
overflow characters are discarded automatically. target[6] = '\0';
printf("target after target[6] = '\\0' = %s\n",
target);
return 0;
}
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
dest
t e s t s \0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
dest
Y i n \0
Function strcat Function strncat
• Function strcat concatenates the destination string • Function strcat concatenates the destination string
with the source string. with the source string. By the specified number of
char dest[15] = “Yin”; characters to append
strcat(dest, “ Yang”); char dest[15] = “Quest”;
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
dest dest
Y i n Y a n g \0 q u e s t \0