C + + removes extra space in a string __c++

Source: Internet
Author: User

Today I wrote a small program to remove the extra spaces in the string, such as "i___am_____a______student." (Underline for empty Geha, dozen spaces to display or one), and final output "I am a student."

Now put your own ideas posted on, Welcome to comment.

The idea is to define two pointers next and tail, one to look for non whitespace characters in the front, another to move in the back step by step, all the characters in the back to the front, and then to remove the extra space, where there are multiple or a space, to leave a space.

#include <iostream>
using namespace std;

char * deletespace (char * str) {
    char * tail = str;
    char * next = str;

    while (*next) {//Two if can be merged together so that it is written simply to look at the convenience
        if (*next!= ') {//Find characters that are not spaces
            *tail = *next;
            tail++;
        }
        if (*next = = ' && * (next-1)!= ') {//the judgment condition of leaving only one space; The current character is a space and the previous one is not a space.
            *tail = *next;
            tail++;
        }
        next++;
    }
    *tail= ' "; String end return
    str;
}

int main () {

    char str[] = "I   am     a    student.";
    Char *res = deletespace (str);
    cout << res << Endl;

    return 0;
}
Related Article

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.