1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 去除字符串中的空格(c++)

去除字符串中的空格(c++)

时间:2018-11-01 04:22:28

相关推荐

去除字符串中的空格(c++)

//去掉首尾空格void trim(string &s){if( !s.empty() ){s.erase(0,s.find_first_not_of(" "));s.erase(s.find_last_not_of(" ") + 1);}}//去掉所有空格void trim(string &s){/*if( !s.empty() ){s.erase(0,s.find_first_not_of(" "));s.erase(s.find_last_not_of(" ") + 1);}*/int index = 0;if( !s.empty()){while( (index = s.find(' ',index)) != string::npos){s.erase(index,1);}}}//去除多余空格/* 思路就是定义两个指针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 ama student.";char *res = deleteSpace(str);cout << res << endl;return 0;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。