Форум » C/C++ для начинающих (C/C++ for beginners) » C programming, deleting leading and trailing spaces » Ответить

C programming, deleting leading and trailing spaces

lordcideon: have to write a c program with a function called trim(). I am to use pointers to delete the spaces before and after the string that i pass, without deleting the spaces between the words. How would i go about doing this? I am not sure what would take away only the leading and trailing spaces. -any help would be appreciated

Ответов - 1

Сыроежка: First of all take into account that though the new line character '\n' is a white space character it shall not be deleted from a string even if it is a trailing character in a string. So you may not use function isspace. Instead you should apply standard function isblank if your compiler supports it. Otherwise you have to compare characters of the string with blank and tab characters yourself. Here is a possible realization of the function within the demonstrative program [pre2] #include <stdio.h> #include <string.h> #include <ctype.h> char * trim( char *s ) { char *p = s; while ( isblank( *p ) ) ++p; char *q = p + strlen( p ); while ( q != p && isblank( *( q - 1 ) ) ) --q; memcpy( s, p, q - p ); s[q - p] = '\0'; return s; } int main(void) { char s[] = " Hello lordcideon! "; printf( "\"%s\"\n", s ); printf( "\"%s\"\n", trim( s ) ); return 0; } [/pre2] The output will be [pre2] " Hello lordcideon! " "Hello lordcideon!" [/pre2] If your compiler does not support function isblank then you should write explicitly for example [pre2] while ( *p == ' ' || *p == '\t' ) ++p; [/pre2] instead of [pre2] while ( isblank( *p ) ) ++p; [/pre2]



полная версия страницы