Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading