50 likes | 163 Views
Examples. Example. Write a program that replaces multiple spaces with one space. while( str [ i ] != '') { if( str [ i ] == ' ') { spc ++; if( spc == 1) putchar ( str [ i ]); } else { spc = 0; putchar ( str [ i ]); } i ++; } printf ("<br>"); return(0); }.
E N D
Example • Write a program that replaces multiple spaces with one space. • while(str[i] != '\0') { • if(str[i] == ' ') { • spc++; • if(spc == 1) putchar(str[i]); • } • else { • spc = 0; • putchar(str[i]); • } • i++; • } • printf("\n"); • return(0); • } • #include <stdio.h> • int main(void) { • char str[80]; • inti=0, spc=0; • gets(str); CENG 114
Example • Write a program that capitalizes the first letter of each word except “and”. • #include <stdio.h> • #include <string.h> • #include <ctype.h> • int main(void) { • char str[80]; • char *wrd; • char *delim = " "; • gets(str); • wrd = strtok(str, delim); • while(wrd!= NULL) { • if(islower(wrd[0]) && strcmp(wrd, "and") != 0) • wrd[0] = toupper(wrd[0]); • printf("%s ", wrd); • wrd = strtok(NULL, delim); • } • printf("\n"); • return(0); • } CENG 114
Example • Write a program substitutes a word with another word in a given sentence • #include <stdio.h> • #include <string.h> • int main(void) { • char str1[80]; • char str2[80]; • char pair[2][10] = {"display", "show"}; • char *stat; • gets(str1); • strcpy(str2, ""); • stat = strtok(str1, " "); • while(stat != NULL) { • if(strcmp(stat, pair[0]) == 0) • strcat(str2, pair[1]); • else • strcat(str2, stat); • strcat(str2, " "); • stat = strtok(NULL, " "); • } • puts(str2); • return(0); • } CENG 114
Example • Write a program which reads 5 names, sorts them, then prints the sorted names • #include <stdio.h> • #include <string.h> • int main(void) { • char Names[5][15]; • char Temp[15]; • inti, j; • for(i=0; i<5; i++) { • printf("Enter name %d: ", i); • scanf("%s", Names[i]); • } • for(i=0; i<4; i++) { • for(j=0; j<4-i; j++) { • if(strcmp(Names[j], Names[j+1]) > 0) { • strcpy(Temp, Names[j]); • strcpy(Names[j], Names[j+1]); • strcpy(Names[j+1], Temp); • } • } • } • for(i=0; i<5; i++) puts(Names[i]); • return(0); • } CENG 114