When you are encountered with a string that has trailing or leading spaces than to remove that i have made a small C snippet.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
char *stripWhitespace (char *inputStr)
{
char *start, *end;
size_t len;
/* Strip leading whitespace */
start = inputStr;
while(*start == ' ') start++;
len = strlen(start);
memmove(inputStr, start, len + 1);
/* Strip trailing whitespace */
end = inputStr + len - 1;
while(end >= inputStr && *end == ' ') end--;
*(end + 1) = '\0';
return inputStr;
}
int main ()
{
clrscr();
char *mystr = " howquest ";
printf("\n\nOriginal String:\n");
puts(mystr);
stripWhitespace(mystr);
printf("\n\nAfter Removing Spaces \n");
puts(mystr);
getch();
return 0;
}
OUTPUT:
- Just copy the code in notepad and save the file with .c or .cpp extension and compile the code using a c Compiler.
- I have used TURBO C-DOS BOX here
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
char *stripWhitespace (char *inputStr)
{
char *start, *end;
size_t len;
/* Strip leading whitespace */
start = inputStr;
while(*start == ' ') start++;
len = strlen(start);
memmove(inputStr, start, len + 1);
/* Strip trailing whitespace */
end = inputStr + len - 1;
while(end >= inputStr && *end == ' ') end--;
*(end + 1) = '\0';
return inputStr;
}
int main ()
{
clrscr();
char *mystr = " howquest ";
printf("\n\nOriginal String:\n");
puts(mystr);
stripWhitespace(mystr);
printf("\n\nAfter Removing Spaces \n");
puts(mystr);
getch();
return 0;
}
OUTPUT:
0 comments:
Post a Comment