Crop a string in C (without using library functions)

I was hoping for some help, against complete solutions, and I have an idea that I need to know what I'm doing wrong when I try to implement.

I'm basically trying to remove spaces from the end of a character array in C.

  • I have a way to work out the length of a string and store it in int.

  • I set the pointer to the first element of my character array.

  • Then I set the pointer to the length of the string - 1 (so as not to get past the index of the array n-1).

  • If the element is not a space here, then I know that there are no spaces at the end, so I just return the element as a whole.

That's where I am stuck, now in a different one, I know that it should have been a run symbol ' 'at the end on the right? Without using the library function, how do I remove this space from the string and continue the loop until I meet a character that is not ' '? A bit bit until I come across a character that is not ' '(space) is simple - it's just a deletion that proves the beast.

Please, not complete solutions, because this is homework, and I do not want to deceive.

+3
source share
6 answers

The trick is that a string in C ends with a NUL character (value 0). This way you can remove the character from the end of the line by simply overwriting it with a null value.

+9
source

  • , , "\ 0" (0x00), "\ 0", - char.
  • . , , , char ( " " ). , .

, .

+5

, '\ 0', , . , , , - , , "\ 0".

0

C .

0

C '\ 0'.

If you have a character pointer

then ...

   *p = 'c';                    and
   *(p  + 0) = 'c';             and
   p[0] = 'c';

everyone writes 'c' in the byte pointed to

.

Continuing this topic ...

   *(p + 1) = 'c';              and
   p[1] = 'c';

both will write 'c' in the byte following the one pointed to

.

0
source

You know the length of the line, so just start at the end of the line and work backward. Whenever you encounter a space, just replace it with a null terminating character, \ 0.

0
source

Source: https://habr.com/ru/post/1733049/


All Articles