Write a c program to replace multiple spaces with single space. For example if the given string is “Hello      wikistack   !” then the output should be “Hello wikistack !”.

Sample c program to replace multiple spaces with single space

#include<stdio.h>
#include<string.h>
#include <ctype.h>

void replace_multiple_space(char* src, char* dst) {

	if (!src)
		return;

	for (; *src; ++dst, ++src) {
		*dst = *src;
		if (isspace(*src))
			while (isspace(*(src + 1)))
				++src;
	}

	*dst = '\0';
}

int main() {

	char str[] = "Hello      wikistack   !";
	int size = strlen(str) + 1;
	char dest[size];
	replace_multiple_space(str, dest);
	printf("%s\n",dest);
	return 0;
}

How it works

  • isspace(int c); returns a nonzero value if c is a white-space character and returns zero if c is not a white-space character.
  • The above program traverses the source string.
  • During traversal we are assigning the characters and a single space to the destination string.
  • We are skipping extra spaces once we find any space using
for (; *src; ++dst, ++src) {
	*dst = *src;
	if (isspace(*src))
	    while (isspace(*(src + 1)))
		++src;
}
  • In the end dest pointer is null terminated to make it c string.

Sample python program to replace multiple spaces with single space

import re
mystr="Hello    wikistack   !"
print re.sub('\s+',' ',mystr)
  • Save the above code as sample.py
  • Make it executable by command ‘chmod +x sample.py’
  • Run using ‘python sample.py’ on Linux terminal.

Ref:

https://www.techonthenet.com/c_language/standard_library_functions/ctype_h/isspace.php



Related Contents to follow