У меня есть простой алгоритм, который очищает пробел от половины строки до конца. Вот оно:
char a[] = "abc "; /* The string to string to trim. */
printf("orginal [%s]\n", a);
char * org = strdup(a); /* duplicate the orginal string */
char * half_str = org + strlen(a) / 2; /* Get the half of string. */
strrev(half_str); /* reverse the string */
char * phs = half_str; /* Point to half_string */
char * news = malloc(strlen(half_str) + 1); /* The new string, without spaces. */
char * ptonews = news; /*Pointer to new string */
while(*phs)
{
/* if it's not whitespace like( ,\f,\r,\t,\v,\n) then concat to new string. */
if(!isspace(*phs)) {
*ptonews ++= *phs;
}
phs ++;
}
/*Put the 0-terminator into new string. */
*phs ++ = '\0';
/* Replace the half_str with the newstring */
strcpy(half_str, news);
printf("new string [%s]\n", org);
работает нормально. вывод:
orginal [abc ]
new string [abc]
Но код на C немного медленный. Как я могу улучшить это?