Originally Posted by
alice
how can I write a program which convert a given string, it removing the leading and trailing space?
Example 1: (Let . be space)
......ABCD....EDE....2dkjl......kll##....
Result should be
ABCD....EDE....2dkjl......kll##
Example 2: (Let . be spare)
...A...WW..22...oo..888....0000...u....
Result should be
A...WW..22...oo..888....0000...u
My think is to use two-dimensional arrays to store the string, for ex.1
......
ABCD
....
EDE
....
2dkjl
......
kll##
....
and then remove the first and end arrays.
Can someone give me some hints on how to write the program? thank a lot.
I wrote a function that might be what you want:
Code:
#include <strings.h>
char *substr(char *buf, const char *start, const char *end, char *result)
{
char *buff;
if ((buff = strstr(buf, start)) == NULL)
return NULL;
while (*buff != *end && *buff != '\0')
*result++ = *buff++;
*result = '\0';
return result;
}
You could call it this way:
Code:
#include <stdio.h>
int main()
{
char buf[1024], result[1024];
FILE *file;
if ((file = fopen("Location of file", "r")) == NULL) {
fprintf(stderr, "fopen: Failed\n");
exit(1);
}
if (fread(buf, 1, sizeof(buf), file) == 0) {
fprintf(stderr, "fread: Failed.\n");
exit(1);
}
if (substr(buf, "A", "#", result) == NULL) { //As per example one
fprintf(stderr, "substr: Failed.\n");
exit(1);
}
if (fclose(file) == EOF) {
fprintf(stderr, "fclose: Failed.\n");
exit(1);
}
fprintf(stdout, "Result = %s\n", result);
return 0;
}