Professional Documents
Culture Documents
h)
Copying:
Concatenation:
strcat - Concatenate string source to destination
Comparison:
strncmp - Compare num characters of source in destination(return 0 if equals, <0 if lesser, >0 if
greater)
size_t strncmp ( const char * str1, const char * str2, size_t num );
Searching:
strchr - returns pointer of first occurrence of character in string (ex: char *pch=strchr(str,'s')str+1;)
char * strchr ( char * str, int character );
Other:
Algorithms
1. Finding occurrences of specific character in string
#include <stdio.h>
#include <string.h>
int main (){
int i;
char strtext[] = "129th";
char cset[] = "1234567890";
i = strspn (strtext,cset);
printf ("%d",i);
}output: 3
2. Finding certain characters in string
#include <stdio.h>
#include <string.h>
int main (){
#include <stdio.h>
#include <string.h>
int x=0;
main (){
char str[] ="101101101101101101101";
char * pch;
pch=strstr(str,"101101");
while(pch!=NULL){
x++;
pch=strstr(pch+1,"101101");
}
printf("%d",x);
}output:6
4. Split based on delimiters
#include <stdio.h>
#include <string.h>
int main (){
char str[] ="- This, a sample string.";
char *pch = strtok (str," ,.-");
while (pch != NULL){
printf ("%s+",pch);
pch = strtok (NULL, " ,.-");
}
}output: This+a+sample+string+
6. Change to uppercase
#include <stdio.h>
#include <ctype.h>
int main (){
int i=0;
char str[]="Test String.\n";
while (str[i]){
if (islower(str[i])) str[i]=toupper(str[i]);
putchar (str[i]);
i++;
}
}output: TEST STRING.