David RF said:
Yes!!
char *trim(const char *orig, char *dest)
Thanks to all posters of this thread
You could try something like this:
__________________________________________________________________
#include <string.h>
#include <assert.h>
#include <ctype.h>
#define xisspace(c) isspace((unsigned char)(c))
char*
trim_string(char* const buffer,
char** const end_buffer)
{
char* cur = buffer;
while (*cur && xisspace(*cur))
{
++cur;
}
if (*cur)
{
char* end = NULL;
char* start = cur;
++cur;
while (*cur)
{
if (xisspace(*cur))
{
if (! end)
{
end = cur;
}
}
else if (end)
{
end = NULL;
}
++cur;
}
if (end_buffer)
{
if (end)
{
*end_buffer = buffer + (end - buffer);
}
else
{
*end_buffer = cur;
}
}
return start;
}
else if (end_buffer)
{
*end_buffer = buffer;
}
return buffer;
}
#include <stdio.h>
void
print_trim_string(char* buffer)
{
char* end;
char const* start = trim_string(buffer, &end);
char tmp = *end;
*end = '\0';
printf("(%lu)->%s<-\n\n",
(unsigned long int)(end - start),
start);
*end = tmp;
}
int main(void)
{
char name1[] = " Hello World! ";
char name2[] = "123 - 456 - 768 ";
char name3[] = " a b c d";
char name4[] = "a b c d";
char name5[] = "Hello";
char name6[] = " ";
char name7[] = "";
trim_string(name1, NULL);
trim_string(name2, NULL);
trim_string(name3, NULL);
trim_string(name4, NULL);
trim_string(name5, NULL);
trim_string(name6, NULL);
trim_string(name7, NULL);
print_trim_string(name1);
print_trim_string(name2);
print_trim_string(name3);
print_trim_string(name4);
print_trim_string(name5);
print_trim_string(name6);
print_trim_string(name7);
return 0;
}
__________________________________________________________________
In this version `trim_string()' does not mutate the caller provided
`buffer'. Instead, it simply returns information on exactly where the
trimmed string starts and ends. The caller can do whatever she/he wants with
this information. As you can see, `print_trim_string()' temporally swaps the
`end' character with a NUL, prints the trimmed string along with it's length
and restores the character it previously swapped out.
This also allows you to easily create another dynamically created buffer if
you wish:
__________________________________________________________________
#include <stdio.h>
#include <stdlib.h>
char*
create_trim_string(char const* buffer)
{
char* const end;
char const* start = trim_string((char*)buffer, (char**)&end);
char* new_buffer = malloc(end - start + 1);
if (new_buffer)
{
memcpy(new_buffer, start, end - start);
new_buffer[end - start] = '\0';
}
return new_buffer;
}
int main(void)
{
char const name1[] = " Hello World! ";
char* buffer = create_trim_string(name1);
puts(buffer);
free(buffer);
return 0;
}
__________________________________________________________________
Any thoughts?