Strings 5

Report
Examples
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");
#include <stdio.h>
int main(void) {
char str[80];
int i=0, spc=0;
gets(str);
return(0);
Dr. Sadık Eşmelioğlu
}
CENG 114
2
Example
• Write a program that capitalizes the first letter
of each word except “and”.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
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");
int main(void) {
char str[80];
char *wrd;
char *delim = " ";
gets(str);
return(0);
}
Dr. Sadık Eşmelioğlu
CENG 114
3
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);
}
Dr. Sadık Eşmelioğlu
CENG 114
4
Example
• Write a program which reads 5 names, sorts
them, then prints the sorted names
#include <stdio.h>
#include <string.h>
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);
}
}
}
int main(void) {
char Names[5][15];
char Temp[15];
int i, j;
for(i=0; i<5; i++) {
printf("Enter name %d: ", i);
scanf("%s", Names[i]);
}
for(i=0; i<5; i++) puts(Names[i]);
return(0);
}
Dr. Sadık Eşmelioğlu
CENG 114
5

similar documents