Home > Software engineering >  Function in C to add <SPACE> after every non space character in a string
Function in C to add <SPACE> after every non space character in a string

Time:02-03

This is what I'm trying to make work

#include <stdio.h>
#include <stdlib.h>

char * xspace(char *s)
{
    int i = 0, j = 0, n = strlen (s);
    char final_string[n];

    for (i; s[i] != '\0'; i  )
    {
        final_string[j] = s[i];

        if(s[i] != ' ')
        {
            final_string[j   1] = ' ';

        }

        j  ;
    }

    final_string[j] = '\0';

    return final_string;
}

int main()
{
    char str[100], final_string[200];

    printf("Enter a string: \n");
    fgets(str, 100, stdin);

    xspace(str);

    printf("\n%s\n", final_string);

}

All I get when trying to run this are random symbols and I can't identify what's causing it. Any help is appreciated

CodePudding user response:

You can do something like this:

#include <stdio.h>
#include <stdlib.h>

char* xspace(char* s)
{
    int i = 0, j = 0;
    const int n = strlen(s);

    // maximum size of this string can be 2*n
    char* final_string= malloc(2 * n);

    // add extra spaces 
    for (i; s[i] != '\0'; i  )
    {
        final_string[j] = s[i];

        if (s[i] != ' ')
        {
            final_string[  j] = ' ';
        }

        j  ;
    }
    final_string[j] = '\0';

    return final_string;
}

int main()
{
    char str[100];

    printf("Enter a string: \n");
    fgets(str, 100, stdin);

    // get final string
    char* final_string = xspace(str);

    // print final string
    printf("\n%s\n", final_string);

    return 0;

}
  •  Tags:  
  • Related