0

I am trying to write a C program which trims any occurrence of white spaces in a string and prints the resultant string.But ain't getting the desired result and I am getting some random symbols as the output. Please help me.

#include<stdio.h>
#include<string.h>
int main()
{
    char s[100];char a[100];int i;
    printf("enter the string:\n");
    gets(s);
    int len=strlen(s);
    for(i=0;i<len;i++)
    {
         if(s[i]!=' ')
         {
             a[i]=s[i];
         }
    }

    for(i=0;i<len;i++)
    {
         printf("%c",a[i]);
    }   
}

Input: Hello Hello

Expected Output: HelloHello.

Current Output:Hello◄Hello

2 Answers2

2

You should copy from s to a, not a to s.

Also use fgets instead of gets, and use isspace to check for white space characters.

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

int main() {
    char s[100];
    char a[100];

    fgets(s, 100, stdin);

    int i = 0;
    int j = 0;
    for (; s[i]; ++i) {
        if (!isspace(s[i])) {
            a[j] = s[i];
            ++j;
        }
    }
    a[j] = '\0'; 

    printf("%s\n", a);
    return 0;
}
Ziming Song
  • 1,176
  • 1
  • 9
  • 22
1
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

/* Function declaration */
void trimTrailing(char * str);


int main()
{
    char str[MAX_SIZE];

    /* Input string from user */
    printf("Enter any string: ");
    gets(str);

    printf("\nString before trimming trailing white space: \n'%s'", str);

    trimTrailing(str);

    printf("\n\nString after trimming trailing white spaces: \n'%s'", str);

    return 0;
}

/**
 * Remove trailing white space characters from string
 */
void trimTrailing(char * str)
{
    int index, i;

    /* Set default index */
    index = -1;

    /* Find last index of non-white space character */
    i = 0;
    while(str[i] != '\0')
    {
        if(str[i] != ' ' && str[i] != '\t' && str[i] != '\n')
        {
            index= i;
        }

        i++;
    }

    /* Mark next character to last non-white space character as NULL */
    str[index + 1] = '\0';
}
GaneSH
  • 543
  • 2
  • 5
  • 16