Share on Google+Share on Google+

C String Remove Spaces

In this section, you will study how to remove spaces from the string.

C String Remove Spaces


In this section, you will study how to remove spaces from the string. You can see in the given example, we have define the string and passed it into two character pointers. The expression p1 = ch, resets the pointer to start. If any punctuation character or whitespace character is found in the *p1 till p1, to be not equal to 0, then ++p1 moves over a whole character otherwise copy the character using the expression *p2++ = *p1++;. The *p2 =

 0; appends the string terminator.

ispunct()- finds the punctuation character.

isspace()-finds the whitespace character.

Here is the code:


#include <stdio.h>
#include <ctype.h>
#include <conio.h>
void main() {
  char ch[80"Where there is will,there is a way.";
  char *p1 = ch;
  char *p2 = ch;
  p1 = ch;
   while(*p1 != 0) {
  if(ispunct(*p1|| isspace(*p1)) {
  *p2++ = *p1++; 
  *p2 = 0
  printf("\nAfter removing the spaces,string is:%s\n", ch);

Output will be displayed as:

Download Source Code:


Posted on: February 5, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: C String Remove Spaces   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
April 5, 2012
C string remove spaces

The code of trim function is very short and easy. But I want to do this two different function for example left trim and right trim. And I want to use return value is a (char *) type. I tried more than one but I always failed. Can you help me, pls?