C++去除字串中多餘的空格__C++

來源:互聯網
上載者:User

今天寫了個小編程,去除字串中多餘的空格,例如"I___am_____a______student."(底線表示空格哈,打多個空格顯示的還是一個),最後輸出”I am a student.”

現在把自己的思路貼上,歡迎大家留言指正。

思路就是定義兩個指標next和tail,一個在前面尋找非空格的字元,另外一個在後面一步一步移動,把後面的字元全部轉移到前面來;然後為了去除多餘的空格,也就是有多個或者一個空格的地方要留一個空格。

#include <iostream>using namespace std;char * deleteSpace(char * str){    char * tail = str;    char * next = str;    while(*next){ // 兩個if可以合并到一塊兒,這樣寫只是為了看著方便        if(*next != ' '){ // 尋找不是空格的字元            *tail = *next;            tail++;        }        if(*next == ' ' && *(next-1) != ' '){ // 只留一個空格的判斷條件;當前字元為空白格且前一個不為空白格。            *tail = *next;            tail++;        }        next++;    }    *tail='\0'; // 字串結束    return str;}int main(){    char str[] = "i   am     a    student.";    char *res = deleteSpace(str);    cout << res << endl;    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.