Friday, May 21, 2010

I need a C code for remove extra spaces from a text (without using the string.h library)?

See the following program I've tested with http://www.delorie.com/djgpp/compile/





Assuming you have a Zero-delimited, char-based ASCII text (i.e. you're using pure ascii, not a unicoded string) you can use the same algorithm:


/*


This program gets the spaced string " spaced " and prints an unspaced string between angles.


Note: this algorithm will modify original string.


*/





#include %26lt;stdio.h%26gt;


int main (void){


/*


This is the original string. Will be overwrited with zeros at its end.


*/


char *trimthis=" spaced ";





/*


This is the destination string:


*/


char *tramthis;





int begin, lasttext, pointer;





/*1- Get first nonspacing char */


begin=0;


while (trimthis[begin]==32) { begin++; }





/*2- Get last nonspacing char */


pointer=begin;


lasttext=pointer;


while (trimthis[pointer]!=0) {


if (trimthis[pointer]!=32)


{


lasttext=pointer;


}


pointer++;


}


/* Get right before the last nonspacing char */


lasttext++;


/* A bit of caution before we overwrite*/


if (lasttext%26gt;pointer) lasttext=pointer;





/* Overwrite just right after the last nonspacing char */


trimthis[lasttext]=0;


(void *)tramthis=(void *)trimthis+begin;





/* Print "%26gt;unspaced%26lt;" from " spaced " */


printf("%26gt;un%s%26lt;",tramthis);





return 0;


}


No comments:

Post a Comment