Sunday, 16 March 2014

How to remove leading and trailing spaces in a string in C

When you are encountered with a string that has trailing or leading spaces than to remove that i have made a small C snippet.

  • 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

Copyright @ 2013 HowQuest.

Join me on Facebook Follow me on Twitter Subscribe to RSS Email me Give it a title