Remove whitespace from a string at a lesser cost

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.