Topic:
Write a function in C, remove the space in the string, and return the number of deleted spaces. No new space is allowed, only simple types of automatic variables can be applied. The time complexity requirement is O (n).
For example:char str[]="Dhkak DF D FD fdjfkda DFD ff f fd da ";
After processing: str[]="dhkakdfdfdfdjfkdadfdffffdda";
The number of deleted spaces returned is: 12
Algorithm idea:
First take the length of the string, and then use a front and back a pointer, respectively, P,Q, so that the front one point to the space, followed by a character, and then replace the previous space with the following value, and then replace with a space, p refers to a space, Q points to the next value, until p points to ' "" , you can get the number of deleted spaces by subtracting the length after processing.
The code is as follows:
1#include <stdio.h>2 intDeletespace (Char*pstr);3 intMain ()4 {5 Charstr[]="Dhkak DF D FD fdjfkda DFD ff f FD da";6 intspaces;7Spaces =deletespace (str);8printf"we have removed%d spaces", spaces);9 return 0;Ten } One intDeletespace (Char*pstr) A { - intLen1 =strlen (PSTR); - Char*p,*Q; thep=pstr; - while(*p!=' ') p++; -q=p; - while(1) + { - while(*q==' '|| *q!=' /') q++; + if(*q==' /') A { at*p=*Q; - Break; - } - Else - { -*p=*Q; in*q=' '; -q++; top++; + } - } the intLen2 =strlen (PSTR); * intCount = len1-Len2; $ returncount;Panax Notoginseng}
This function can be implemented with the time complexity of O (n).
Remove whitespace from a string at a lesser cost