The C code you turn in should not use any of the built-in string functions. trim
ID: 3542532 • Letter: T
Question
The C code you turn in should not use any of the built-in string functions.
trim: Remove the trailing newline
Strings often contain a newline character, such as those returned by fgets. Often, you want to get rid of that extra newline. The trim function should remove this trailing newline character (if it exists) by replacing it with a null-terminator character. There is no equivalent built-in function. This is a handy one to write for our own uses.
The signature is:
void trim(char *s)
There are 5 cases to test:
A normal string, with a single newline at the end. Remove it.
A string with more than more newline, but the last one is at the end. Remove the last one.
A string with a newline not at the end. Leave as-is.
A string with no newlines at all. Leave as-is.
A string that consists of only a newline. Remove it.
Explanation / Answer
please rate - thanks
#include <stdio.h>
#include <conio.h>
void trim(char *s);
int main(void)
{char one[]={"this is case 1 "};
char two[]={"this is case 2 "};
char three[]={"this is case 3"};
char four[] ={"this is case 4"};
char five[]={" "};
printf("all cases before ");
printf("case 1: %s ",one );
printf("case 2: %s ",two );
printf("case 3: %s ",three);
printf("case 4: %s ",four );
printf("case 5: %s ",five );
trim(one);
trim(two);
trim(three);
trim(four);
trim(five);
printf(" all cases after ");
printf("case 1: %s ",one );
printf("case 2: %s ",two );
printf("case 3: %s ",three);
printf("case 4: %s ",four );
printf("case 5: %s ",five );
getch();
return 0;
}
void trim(char *s)
{int i;
i=0;
while(s[i]!='')
i++;
if(s[i-1]==' ')
s[i-1]='';
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.