removing blanks from a string in c - c

I know its a question that been asked many times before, but i'm not asking for the solution itself, but to know why my solution isn't working.
this is my solution:
void delete_blanks(char *string)
{
while (*string)
{
if (*string == ' ')
*string = '\0';
*string++;
}
puts(string);
}
The program just printing blanks (" ") for every input.
while running with the debugger, I saw that *string is pointing for '\0' at the end. Is it possible to do it "in-place"?
This is the original solution found here:
void RemoveSpaces(char* source)
{
char* i = source;
char* j = source;
while(*j != 0)
{
*i = *j++;
if(*i != ' ')
i++;
}
*i = 0;
}

Here is a good in-place implementation
int main(void) {
char inStr[] = "a cat is on the moon";
int end = 0;
for (int i = 0; i < strlen(inStr); i++) {
if (inStr[i] != ' ') {
if (i != end) {
inStr[end] = inStr[i];
}
end++;
}
}
inStr[end] = '\0';
printf("%s\n", inStr);
}

Probably because you are modifying the source, the parameter passed to that function, when it looks for spaces, shortcut the source to '\0', so you are not printing the correct result. try to use other pointers like the examples you give.

char a[]="it is a sunny morning";
int j=0;
for( int i=0;i<strlen(a);i++){
if(a[i]!=' '){
a[j]=a[i];
j++;
}
}
for(int i=j;i<strlen(a);i++){
a[i]='\0';
}
printf("%s",a);
first group the letters without space then remove the letters that exceeds the space.
output
itisasunnymorning

It's unclear what you mean by "removing the blanks". If all you want to do is print the string without the spaces, you could reduce you function to this:
void delete_blanks(char *string)
{
while (*string)
{
if (*string != ' ')
putchar(*string);
string++;
}
putchar('\n');
}
If you want to remove the spaces in the underlying string it becomes a bit more complex as you would have to move characters after a ' ' to fill in the gaps. There is no 'empty character' you can insert to fill the hole in the string, you must move the remaining characters to fill it.
Basically there a 2 major things wrong with your function. You are replacing spaces with string terminating characters, signaling that the string ends here. This is not what you want to do as there might be characters after the space. In fact, if you only want to print the string you should not be modifying it at all.
When you are done iterating over the string, string points to the end of the string. Essentially passing an empty string to puts(). You need to pass the original value, before you did a lot of ++ on it, to puts()
You are also doing *string++ when you should really be doing string++. This actually works since it is parsed as *(string++) but is terrible for readability.

If you want to remove the spaces between the words of a string,
the direct answer as follows:
// #include <ctype.h>
void RemoveSpaces(char *str) {
char *strBuff = (char*) malloc(strlen(str) + 1), *p = strBuff;
while (*str) {
if (!isspace(*str)) {
*p = *str;
p++;
}
str++;
}
*p = '\0';
printf("%s\n", strBuff);
free(strBuff);
}
int main(){
RemoveSpaces("Thank you for help");
}
The Result:
Also, there is another way and gives the same result as follows:
void RemoveSpaces(char *str) {
while (*str) {
if (!isspace(*str)) {
putchar(*str);
}
str++;
}
printf("%s\n", str);
}

Related

Returning the rest of a string in c after the first white space

I'm writing a program to return a the rest of a string after the first white space.
"I had a bad day"
should return
"had a bad day"
This is what I have so far
char* next_word(char* str){
char s[100];
int index = 0;
int i = 0;
int counter = 0;
for(i = 0; i < strlen(str); i++){
if(str[i] == ' '){
index = i+1;
for(index; index < strlen(str); index++){
s[counter] = str[index];
counter = counter + 1;
}
s[index] = '\0';
return s;
}
}
return index;
}
I'm looping through the char* str and finding the index of the first empty space then from there I've made another loop to print out the rest of the string starting at index + 1. For some reason when I writes s[counter] = str[index], I don't believe that its copying the char from str to s.
When I try to return s after the loop I don't get anything. Is it possible to add char to the empty char s[100] then return the full string as s?
Thank You
Your next_word() function is returning a local (to the function) variable which results in a undefined behavior. You must take s (in your case) as input or malloc a character buffer in the function. Then you can do the copying. I prefer you go for the first alternative and do not forget to check the length of the input string, so that you do not cross the size while copying.
Also, the next_word() returns index when no space found? That is clearly a mistake and your code will fail to compile.
For the code, you can just break from the first loop whenever you find the first space and from there you can continue with copying.
You should not return s as it is a local variable on the stack. You could simply return a pointer into the str argument since str remains valid at the time of return.
#include <string.h>
const char* TheString = "I had a bad day";
const char* stringAfterBlank(const char* str)
{
const char* blank = strchr(str, ' ');
if (blank != NULL)
{
return ++blank;
}
return "";
}
void main(int argc, char** argv)
{
const char* restOfTheString = stringAfterBlank(TheString);
// restOfTheString is "had a bad day" pointing into TheString
}
If you need a copy of the string then you can use strdup. If you do then don't forget to free.
You shouldn't return your local variable. The easiest way to accomplish what you want is operating on pointers.
There is solution using only stdio.h, as you wanted:
#include <stdio.h>
char* next_word(char* str);
int main()
{
char* arg = "I had a bad day!";
//Print every "next_word"
char* words = arg;
do{
printf("%s\n", words);
} while(words = next_word(words));
}
char* next_word(char* str)
{
while(*str != '\0'){
if(*str++ == ' ')
return str;
}
return NULL;
}

Searching an array for a specific character [duplicate]

I want to write a program in C that displays each word of a whole sentence (taken as input) at a seperate line. This is what I have done so far:
void manipulate(char *buffer);
int get_words(char *buffer);
int main(){
char buff[100];
printf("sizeof %d\nstrlen %d\n", sizeof(buff), strlen(buff)); // Debugging reasons
bzero(buff, sizeof(buff));
printf("Give me the text:\n");
fgets(buff, sizeof(buff), stdin);
manipulate(buff);
return 0;
}
int get_words(char *buffer){ // Function that gets the word count, by counting the spaces.
int count;
int wordcount = 0;
char ch;
for (count = 0; count < strlen(buffer); count ++){
ch = buffer[count];
if((isblank(ch)) || (buffer[count] == '\0')){ // if the character is blank, or null byte add 1 to the wordcounter
wordcount += 1;
}
}
printf("%d\n\n", wordcount);
return wordcount;
}
void manipulate(char *buffer){
int words = get_words(buffer);
char *newbuff[words];
char *ptr;
int count = 0;
int count2 = 0;
char ch = '\n';
ptr = buffer;
bzero(newbuff, sizeof(newbuff));
for (count = 0; count < 100; count ++){
ch = buffer[count];
if (isblank(ch) || buffer[count] == '\0'){
buffer[count] = '\0';
if((newbuff[count2] = (char *)malloc(strlen(buffer))) == NULL) {
printf("MALLOC ERROR!\n");
exit(-1);
}
strcpy(newbuff[count2], ptr);
printf("\n%s\n",newbuff[count2]);
ptr = &buffer[count + 1];
count2 ++;
}
}
}
Although the output is what I want, I have really many black spaces after the final word displayed, and the malloc() returns NULL so the MALLOC ERROR! is displayed in the end.
I can understand that there is a mistake at my malloc() implementation, but I do not know what it is.
Is there another more elegant or generally better way to do it?
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.
From the website:
char * strtok ( char * str, const char * delimiters );
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.
Parameters
str
C string to truncate.
Notice that this string is modified by being broken into smaller strings (tokens).
Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
delimiters
C string containing the delimiter characters.
These may vary from one call to another.
Return Value
A pointer to the last token found in string.
A null pointer is returned if there are no tokens left to retrieve.
Example
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
For the fun of it here's an implementation based on the callback approach:
const char* find(const char* s,
const char* e,
int (*pred)(char))
{
while( s != e && !pred(*s) ) ++s;
return s;
}
void split_on_ws(const char* s,
const char* e,
void (*callback)(const char*, const char*))
{
const char* p = s;
while( s != e ) {
s = find(s, e, isspace);
callback(p, s);
p = s = find(s, e, isnotspace);
}
}
void handle_word(const char* s, const char* e)
{
// handle the word that starts at s and ends at e
}
int main()
{
split_on_ws(some_str, some_str + strlen(some_str), handle_word);
}
malloc(0) may (optionally) return NULL, depending on the implementation. Do you realize why you may be calling malloc(0)? Or more precisely, do you see where you are reading and writing beyond the size of your arrays?
Consider using strtok_r, as others have suggested, or something like:
void printWords(const char *string) {
// Make a local copy of the string that we can manipulate.
char * const copy = strdup(string);
char *space = copy;
// Find the next space in the string, and replace it with a newline.
while (space = strchr(space,' ')) *space = '\n';
// There are no more spaces in the string; print out our modified copy.
printf("%s\n", copy);
// Free our local copy
free(copy);
}
Something going wrong is get_words() always returning one less than the actual word count, so eventually you attempt to:
char *newbuff[words]; /* Words is one less than the actual number,
so this is declared to be too small. */
newbuff[count2] = (char *)malloc(strlen(buffer))
count2, eventually, is always one more than the number of elements you've declared for newbuff[]. Why malloc() isn't returning a valid ptr, though, I don't know.
You should be malloc'ing strlen(ptr), not strlen(buf). Also, your count2 should be limited to the number of words. When you get to the end of your string, you continue going over the zeros in your buffer and adding zero size strings to your array.
Just as an idea of a different style of string manipulation in C, here's an example which does not modify the source string, and does not use malloc. To find spaces I use the libc function strpbrk.
int print_words(const char *string, FILE *f)
{
static const char space_characters[] = " \t";
const char *next_space;
// Find the next space in the string
//
while ((next_space = strpbrk(string, space_characters)))
{
const char *p;
// If there are non-space characters between what we found
// and what we started from, print them.
//
if (next_space != string)
{
for (p=string; p<next_space; p++)
{
if(fputc(*p, f) == EOF)
{
return -1;
}
}
// Print a newline
//
if (fputc('\n', f) == EOF)
{
return -1;
}
}
// Advance next_space until we hit a non-space character
//
while (*next_space && strchr(space_characters, *next_space))
{
next_space++;
}
// Advance the string
//
string = next_space;
}
// Handle the case where there are no spaces left in the string
//
if (*string)
{
if (fprintf(f, "%s\n", string) < 0)
{
return -1;
}
}
return 0;
}
you can scan the char array looking for the token if you found it just print new line else print the char.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
int len = strlen(s);
char delim =' ';
for(int i = 0; i < len; i++) {
if(s[i] == delim) {
printf("\n");
}
else {
printf("%c", s[i]);
}
}
free(s);
return 0;
}
char arr[50];
gets(arr);
int c=0,i,l;
l=strlen(arr);
for(i=0;i<l;i++){
if(arr[i]==32){
printf("\n");
}
else
printf("%c",arr[i]);
}

Removing spaces from a string

I am trying to copy from one string to another, but the second string should omit the space. I tried to approach this by saying, if a character in the original string is a space, do not copy it. Instead, copy the next character. However, the program deletes everything after the space. Any ideas?
char deleteSpaces(char phrase[256], int length){
int j, i=0;
char phrase2[length];
for(j=0;j<length;j++){
if(phrase[i]==' '){
phrase2[j]=phrase[i+1];
i++;
}
phrase2[j]=phrase[i];
}
return phrase2;
}
Here is a solution:
void deleteSpaces(char src[], char dst[]){
// src is supposed to be zero ended
// dst is supposed to be large enough to hold src
int s, d=0;
for (s=0; src[s] != 0; s++)
if (src[s] != ' ') {
dst[d] = src[s];
d++;
}
dst[d] = 0;
}
First, you're returning a static tab and this is wrong.
Secondly you don't increment 'i' if there is no space.
And to finish you will copy spaces if there is more than one space in a row. And you do not control if you reach the end of your source.
for(j = 0; j < length; j++)
{
while (src[i] == ' ' && i < length) i++;
if (i < length)
dest[j] = src[i++];
else
{
dest[j] = 0;
break;
}
}
My solution. Arguments and their order are chosen to match strncpy().
#include <ctype.h>
char *strip_whitespace(char *dest, const char *src, size_t n)
{
char *s, *d;
/*
* Copy 'src' to 'dest', omitting whitespace and making sure we don't
* overflow 'dest'.
*/
for(s=src, d=dest; *s && (d-dest)<n; s++) {
if( !isspace(*s) ) {
*d = *s;
d++;
}
}
/* Ensure that dest is NUL terminated in any event */
if( d-dest < n ) {
*d = '\0';
} else {
dest[n-1] = '\0';
}
return dest;
}
As pointed out already you need to allocate a new string and return a pointer to it. This code works:
char* strip (char* input)
{
int loop;
char *output = (char*) malloc (strlen(input));
char *dest = output;
if (output)
{
for (loop=0; loop<strlen(input); loop++)
if (input[loop] != ' ')
*dest++ = input[loop];
*dest = '\0';
}
return output;
}
int main (void)
{
char srcString[] = " this is a test with spaces at the end ";
char* dstString = strip (srcString);
printf ("source string = '%s'\n", srcString);
printf (" dest string = '%s'\n", dstString ? dstString : "malloc failed in strip");
free (dstString);
return 0;
}
Output:
source string = ' this is a test with spaces at the end '
dest string = 'thisisatestwithspacesattheend'
It takes the input string and allocates a destination string the same size which is safe, although wasteful of a few bytes.
The method is simple; only copy a character if it is not a space. After all the characters are copied, I write the terminator on the end and return the pointer.
****WHAT YOU WERE DOING** IS THAT if a character in the original string is a space, do not copy it. Instead, copy the next character. IS NOT A GOOD idea because
Case 1. When multiple spaces are present, it simply discard the first spaces and copies the second one...
Case 2: Your programme copies the string only after space is found,,it is simply skipping the first word of string which doesn't start with spaces.
case 3. You are only returning the character pointed by phrase2[0] as return type is char,and the scope of local variable is limited to only that function....
//the corrected programme
int deleteSpaces(char phrase[256],charphrase2[256])
{
int i,j;
i=j=0;
while(phrase[i]!=NULL){
if(phrase[i]!=' '){
phrase2[j]=phrase[i];
j++;
}
i++;
}//end while
phrase2[j]=phrase[i] //nulcharceter copied
return 0;
}//end deleteSpaces function
I use this:
char input[100], foreval[100];
for(i=0;i<strlen(input);i++){
if(isspace(input[i])){
continue;
}
strncat(foreval,&input[i],1);
}

Split string in C every white space

I want to write a program in C that displays each word of a whole sentence (taken as input) at a seperate line. This is what I have done so far:
void manipulate(char *buffer);
int get_words(char *buffer);
int main(){
char buff[100];
printf("sizeof %d\nstrlen %d\n", sizeof(buff), strlen(buff)); // Debugging reasons
bzero(buff, sizeof(buff));
printf("Give me the text:\n");
fgets(buff, sizeof(buff), stdin);
manipulate(buff);
return 0;
}
int get_words(char *buffer){ // Function that gets the word count, by counting the spaces.
int count;
int wordcount = 0;
char ch;
for (count = 0; count < strlen(buffer); count ++){
ch = buffer[count];
if((isblank(ch)) || (buffer[count] == '\0')){ // if the character is blank, or null byte add 1 to the wordcounter
wordcount += 1;
}
}
printf("%d\n\n", wordcount);
return wordcount;
}
void manipulate(char *buffer){
int words = get_words(buffer);
char *newbuff[words];
char *ptr;
int count = 0;
int count2 = 0;
char ch = '\n';
ptr = buffer;
bzero(newbuff, sizeof(newbuff));
for (count = 0; count < 100; count ++){
ch = buffer[count];
if (isblank(ch) || buffer[count] == '\0'){
buffer[count] = '\0';
if((newbuff[count2] = (char *)malloc(strlen(buffer))) == NULL) {
printf("MALLOC ERROR!\n");
exit(-1);
}
strcpy(newbuff[count2], ptr);
printf("\n%s\n",newbuff[count2]);
ptr = &buffer[count + 1];
count2 ++;
}
}
}
Although the output is what I want, I have really many black spaces after the final word displayed, and the malloc() returns NULL so the MALLOC ERROR! is displayed in the end.
I can understand that there is a mistake at my malloc() implementation, but I do not know what it is.
Is there another more elegant or generally better way to do it?
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.
From the website:
char * strtok ( char * str, const char * delimiters );
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.
Parameters
str
C string to truncate.
Notice that this string is modified by being broken into smaller strings (tokens).
Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
delimiters
C string containing the delimiter characters.
These may vary from one call to another.
Return Value
A pointer to the last token found in string.
A null pointer is returned if there are no tokens left to retrieve.
Example
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
For the fun of it here's an implementation based on the callback approach:
const char* find(const char* s,
const char* e,
int (*pred)(char))
{
while( s != e && !pred(*s) ) ++s;
return s;
}
void split_on_ws(const char* s,
const char* e,
void (*callback)(const char*, const char*))
{
const char* p = s;
while( s != e ) {
s = find(s, e, isspace);
callback(p, s);
p = s = find(s, e, isnotspace);
}
}
void handle_word(const char* s, const char* e)
{
// handle the word that starts at s and ends at e
}
int main()
{
split_on_ws(some_str, some_str + strlen(some_str), handle_word);
}
malloc(0) may (optionally) return NULL, depending on the implementation. Do you realize why you may be calling malloc(0)? Or more precisely, do you see where you are reading and writing beyond the size of your arrays?
Consider using strtok_r, as others have suggested, or something like:
void printWords(const char *string) {
// Make a local copy of the string that we can manipulate.
char * const copy = strdup(string);
char *space = copy;
// Find the next space in the string, and replace it with a newline.
while (space = strchr(space,' ')) *space = '\n';
// There are no more spaces in the string; print out our modified copy.
printf("%s\n", copy);
// Free our local copy
free(copy);
}
Something going wrong is get_words() always returning one less than the actual word count, so eventually you attempt to:
char *newbuff[words]; /* Words is one less than the actual number,
so this is declared to be too small. */
newbuff[count2] = (char *)malloc(strlen(buffer))
count2, eventually, is always one more than the number of elements you've declared for newbuff[]. Why malloc() isn't returning a valid ptr, though, I don't know.
You should be malloc'ing strlen(ptr), not strlen(buf). Also, your count2 should be limited to the number of words. When you get to the end of your string, you continue going over the zeros in your buffer and adding zero size strings to your array.
Just as an idea of a different style of string manipulation in C, here's an example which does not modify the source string, and does not use malloc. To find spaces I use the libc function strpbrk.
int print_words(const char *string, FILE *f)
{
static const char space_characters[] = " \t";
const char *next_space;
// Find the next space in the string
//
while ((next_space = strpbrk(string, space_characters)))
{
const char *p;
// If there are non-space characters between what we found
// and what we started from, print them.
//
if (next_space != string)
{
for (p=string; p<next_space; p++)
{
if(fputc(*p, f) == EOF)
{
return -1;
}
}
// Print a newline
//
if (fputc('\n', f) == EOF)
{
return -1;
}
}
// Advance next_space until we hit a non-space character
//
while (*next_space && strchr(space_characters, *next_space))
{
next_space++;
}
// Advance the string
//
string = next_space;
}
// Handle the case where there are no spaces left in the string
//
if (*string)
{
if (fprintf(f, "%s\n", string) < 0)
{
return -1;
}
}
return 0;
}
you can scan the char array looking for the token if you found it just print new line else print the char.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
int len = strlen(s);
char delim =' ';
for(int i = 0; i < len; i++) {
if(s[i] == delim) {
printf("\n");
}
else {
printf("%c", s[i]);
}
}
free(s);
return 0;
}
char arr[50];
gets(arr);
int c=0,i,l;
l=strlen(arr);
for(i=0;i<l;i++){
if(arr[i]==32){
printf("\n");
}
else
printf("%c",arr[i]);
}

How do I replace multiple spaces with a single space?

Well I'm looking for a function that reduce multiple space characters ' ' in a string.
For example for string s given :
s="hello__________world____!"
The function must return "hello_world_!"
In python we can do it via regexp simply as:
re.sub("\s+", " ", s);
A version that modifies the string in place, run it on a copy if the original must be preserved:
void compress_spaces(char *str)
{
char *dst = str;
for (; *str; ++str) {
*dst++ = *str;
if (isspace(*str)) {
do ++str;
while (isspace(*str));
--str;
}
}
*dst = 0;
}
There is no such function in the C standard library. One must write a function to do so or use a third-party library.
The following function should do the trick. Use the source string as the destination pointer to perform the operation in place. Otherwise, ensure that the destination buffer is sufficiently sized.
void
simplifyWhitespace(char * dst, const char * src)
{
for (; *src; ++dst, ++src) {
*dst = *src;
if (isspace(*src))
while (isspace(*(src + 1)))
++src;
}
*dst = '\0';
}
void remove_more_than_one_space(char *dest, char *src)
{
int i, y;
assert(dest && src);
for(i=0, y=0; src[i] != '\0'; i++, y++) {
if(src[i] == ' ' && src[i+1] == ' ') {
/* let's skip this copy and reduce the y index*/
y--;
continue;
}
/* copy normally */
dest[y] = src[i];
}
dest[y] = '\0';
}
int main()
{
char src[] = "Hello World ! !! !";
char dest[strlen(src) + 1];
remove_more_than_one_space(dest, src);
printf("%s\n", dest);
}
I just made this, hope it helps.
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
char word[100];
gets(word);
//the word has more than a single space in between the words
int i=0,l,j;
l=strlen(word);
for (i=0;i<l;i++)
{
if(word[i]==' '&&word[i+1]==' ')
{
for(j=i+1;j<l;j++)
word[j]=word[j+1];
}
}
puts(word);
return 0;
}
This code is very simple and it worked like a charm for me. I don't know if this code will have some other problems I haven't come across, but for now this works.
I'm just learning C, so I'm using much more basic code. I'm reading the first chapter of "The C programming language", and I was trying to find the answer to a task set in there.
This is what I came up with:
#include <stdio.h>
int main()
{
/* Set two integers:
c is the character being assessed,
lastspace is 1 if the lastcharacter was a space*/
int c, lastspace;
lastspace = 0;
/* This while loop will exit if the character is EOF
The first "If block" is true if the character is not a space,
and just prints the character
It also tells us that the lastcharacter was not a space
The else block will run if the character is a space
Then the second IF block will run if the last character
was not also a space (and will print just one space) */
while((c = getchar()) != EOF){
if (c != ' '){
putchar(c);
lastspace = 0;
}
else {
if (lastspace != 1)
putchar(c);
lastspace = 1;
}
}
return 0;
}
Hope that helps!
Also, I am well aware that this code is perhaps not optimised, but it should be simple for a beginner like me to understand!
Thanks, Phil
another way of doing this to print only the first occurrence of space until next character comes, here is my brute force solution.
#include<stdio.h>
typedef int bool;
#define True 1
#define False 0
int main()
{
int t;
bool flag = False;
while ((t = getchar()) != EOF)
if (t == ' ' && !flag)
{
putchar(' ');
flag = True; // flag is true for the first occurence of space
}
else if(t == ' '&& flag)
continue;
else
{
putchar(t);
flag = False;
}
return 0;
}
hope it helps.

Resources