Professional Documents
Culture Documents
Algorithm and Programming GSLC Assignment Session 10
Algorithm and Programming GSLC Assignment Session 10
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)
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