Career Cup 1-5

/*******************************************************

    Write a method to replace all spaces in a string with ‘%20’

  Note:  every space is replaced with 3 characters, causing the extension of the string by 2 * SpCnt.

  Complexity: O(2n)

  Mod Time: 4.20, 2012

  Copyright: Ben

  *******************************************************/

#include<stdio.h>
#include<stdlib.h>

#define STRING_MAX_LEN            10000

int main(void)
{
    int i, j, Offset;
    char s[STRING_MAX_LEN];
    char ch;
    //this marks the indices of <sp>
    int sp[STRING_MAX_LEN / 2];    //in case all char are spaces.
    //number of <sp>
    int SpCnt = 0;
    int StLen = 0;

    freopen("String.txt", "r", stdin);

    //keep reading until the end of file.
    while((ch = fgetc(stdin)) != EOF)
    {        
        if(ch == ' ')
        {
            sp[SpCnt++] = StLen;
        }
        s[StLen++] = ch;
    }

    s[StLen] = '\0';
    sp[SpCnt] = StLen;    //the pseudo count.

    printf("Original:%s\n", s);

    //the final char is separately handled.
    s[sp[SpCnt] + SpCnt * 2] = '\0';
    //replacement
    for(i = SpCnt; i > 0; i--)
    {
        Offset = i * 2;
        for(j = sp[i] - 1; j > sp[i - 1] ; j--)
        {
            s[j + Offset] = s[j];            
        }

        //replace <sp> with "%20"
        s[sp[i - 1] + Offset] = '0';
        s[sp[i - 1] + Offset - 1] = '2';
        s[sp[i - 1] + Offset - 2] = '%';
    }

    printf("Modified:%s\n", s);

    fclose(stdin);

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值