A
A
Anther2020-11-21 01:18:05
C++ / C#
Anther, 2020-11-21 01:18:05

Where do gaps come from?

The program must remove spaces at the beginning and at the end of the string. In a function, it does its job, but when it returns to main, it breaks.

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

int size(const char str[])
{
    int i = 0;
    while(str[i] != '\0')
    {
        i++;
    }
    return i;
}

void mutableStrip(char str[])
{
    int start = 0;
    while(str[start] == ' ')
    {
        start++;
    }

    int n = size(str);
    int end = 0;
    while(str[(n-1) - end] == ' ')
    {
        end++;
    }

    str[n-end] = '\0';
    str += start;

    printf("0%s1 \n", str);
}

int main()
{
    char str[] = "  ads  fh ";

    mutableStrip(str);
    printf("0%s1 \n", str);
    return 0;
}


conclusion:
0ads  fh1
0  ads  fh1

Added 0 and 1 to show where the line starts and ends.

For some reason, spaces appear in the main, although there are none in the function.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2020-11-21
@Anther

Great, the answer was deleted...
So, once again: str is a pointer, it is passed to the function by value, you cannot change it, this does not affect str after returning from the function:
str += start;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question