You are on page 1of 3

Algorithm and Programming

STRING
Nama: Aryo Prasetyo
NIM: 2602062601
Describe some functions of <string.h>:

·        strcpy(s1, s2)

·        strcat(s1, s2)

·        strcmp(s1, s2)

·        strlen(s)

·        strchr(s, c)

·        strstr(s1, s2)

·        strtok(s1, s2)

Provide an example for each function.

strcpy(s1,s2) is a function to copy the string in s2 into s1.


Example:
char s1[10]=”binus”;
char s2[10]=”spirit”;
strcpy(s1,s2);
printf(“%s\n”, s1);
output:
spirit

strcat(s1,s2) is a function to add string 2 (s2) to the end of string 1 (s1).


Example:
char s1[10]=”binus”;
char s2[10]=”spirit”;
strcat(s1,s2);
printf(“%s\n”, s1);
output:
binusspirit
strcmp(s1,s2) is a function used to compare the value of string 1(s1) and string 2(s2). If
string 1 and string 2 is similar, the return value will be 0.
Example:
char s1[10]=”spirit”;
char s2[10]=”spirit”;
int temp;
temp = strcmp(s1,s2);
printf(“%d\n”, temp);
output:
0

strlen(s) is a function used to calculate the length of a string excluding the null char.
Example:
char s[10]=”spirit”;
int temp;
temp = strlen(s);
printf(“%d\n”, temp);
output:
6

strchr(s,c) is a function used to search for the first occurrence of a specified character (c) in
string (s). If c is found within s, it returns a pointer value; otherwise it returns a null pointer.
Example:
char s[10]=”spirit”;
char c=’s’;
char *ptr;
ptr=strchr(s,c);
printf(“%s\n”, ptr);
output:
pirit
strstr(s1,s2) is a function used to search for the first occurrence of the substring (s2) in the
string (s1). If s2 is found within s1, it returns a pointer value of s2; otherwise it returns a null
pointer.
Example:
char s1[20]=”BinusSpirit”;
char s2[10]=”Spirit”;
char *ptr;
ptr=strstr(s1,s2);
printf(“%s\n”, ptr);
output:
Spirit

strtok(s1,s2) is a function used to breaks string 1 (s1) into a series of token using string 2
(s2).
Example:
char s1[100] = "Striving For Excelence-Preseverence-Integrity-Respect-Innovation";
char s2[100] = "-";
char *res;
res = strtok(s1, s2);
while(res != NULL)
{
printf("%s\n", res);
res = strtok(NULL,s2);
}
output:
Striving For Excelence
Preseverence
Integrity
Respect
Innovation

You might also like