Monday, December 11, 2006

Remove those spaces!!

Its been a long time since I have posted something new and useful...well have been really busy with life!!

Here is a code I wrote for fun...it removes all the multiple tabs and blank spaces in a string.

Feel free to use it, but do give credit to the Author :)
And if you find any issues...or feel like giving some feed back...you are most welcome!!



/*
* Date: 10th December 2006
* Simple Utility code written by hundredrabh
* It simply removes more than 4 spaces and tab stops
* from the input string and replaces them with space.
* You can download and play with the code
* But please do give due credit to the author for his efforts!!
* Happy Coding
*/

#include "stdio.h"
#include "stdlib.h"

/* Function declaration and defination */

/* char* enterString(char*)
* Accepts a char pointer, to return the input string
* returns a pointer to the input string, and this pointer needs to be freed by the user!
* Error checking needs to be added for return values and realloc
// TODO - Enhance it for buffered reading/writing
// As realloc is slow....
*/
char*
enterString(char* str)
{
char ch;
int len = 0;
while(10 != (ch = fgetc(stdin)))
{
if(0 == (len % 512)) {
str = (char*)realloc(str, len + 513); // TODO - Need Error Checking here...
}
*(str + len) = ch;
*(str + len + 1) = '\0'; // adding the null termination as realloc does not return 0ed memory..so EOS determination is difficult.
++len;
}
return str; // This needs to be freed by the user
}

/* End of enterString(char*) */

/* DETAB
* void detab(const char*)
* returns a void, accepts a char*
* remove all the tab spaces or spaces which are in multiples of 4 from the string
* Spaces before and after a tab will be considered as continuous!!
*
*/
void
detab(char* str)
{
char* dummyRetStr = str;
int spaces = 0;
while(*str)
{
switch(*str)
{
case '\t': // Remove the tab
*str = ' ';
++spaces;
break;
// check for 4 spaces together
case ' ' :
++spaces;
break;
default :
spaces = 0;
break;
}
*dummyRetStr++ = *str++;
if(spaces == 4) dummyRetStr -=3, spaces =1; // Remove 4 spaces occuring together!
}
*dummyRetStr = '\0'; // null terminate the modified string
}


int
main()
{
char *inp = 0;
printf("Enter the string \n");

inp = enterString(inp); // Free inp, it has been malloced
detab(inp);

printf("You entered .... %s\n", inp);
realloc(inp, 0);
return 0;
}

No comments: