Problem of removing spaces using c language strtok

Asked 2 years ago, Updated 2 years ago, 34 views

I want to create a function that takes a string and deletes all blank characters using strtok It ends immediately.

Enter: "abcdef"

Desired output: "abcdef"

Actual Output: "ab"

I want to solve it using strtok, how can I modify it?

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

void Split(char *arr);
int main(void)
{
    char a[20];

    printf ("Enter String");
    scanf("%s", a);
    Split(a);

    return 0;
}

void Split(char *arr)
{
    char *tk;
    tk = strtok(arr, " ");

    while(tk != NULL)
    {
        printf("%s", tk);
        tk = strtok(NULL, " ");
    }
}

c

2022-09-22 19:46

1 Answers

The scanf function seems to be a problem because the input ends when a blank character is entered.

When I changed scanf to gets_s() function, the results you wanted came out :)

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

void Split(char *arr);
int main(void)
{
    char a[20];

    printf ("Enter String");
    changes to get_s(a); // scanf function to get_s function
    Split(a);

    return 0;
}

void Split(char *arr)
{
    char *tk;
    tk = strtok(arr, " ");
    while (tk != NULL)
    {
        printf("%s", tk);
        tk = strtok(NULL, " ");
    }
}


2022-09-22 19:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.