替换空格

题目大意:在原串上,将字符串中‘ ’转化成%20后输出。

思路:计算出空格个数,从后往前处理

#include<stdio.h>
#include <iostream>
#include<stack>
#include<string.h>
#include<queue>
using namespace std;
const int maxn = 1e4+200;
char s[15000];
void trans(){
    int len = strlen(s);
    int num = 0;
    for(int i = 0; i < len; ++i){
        if(s[i] == ' ') ++num;
    }
    for(int i = len, j = len+2*num; i >= 0; ){
        if(s[i] == ' '){
            s[j] = '0';
            s[j-1] = '2';
            s[j-2] = '%';
            j -= 3;
            --i;
        }else{
            s[j] = s[i];
            --j; --i;
        }
    }
}
int main(){
    while(gets(s)){
        trans();
        puts(s);
    }
    return 0;
}

/*
i you

we are happy.
*/

  

原文地址:https://www.cnblogs.com/chengsheng/p/5608655.html