您的位置:首页 > 编程语言 > C语言/C++

CTCI系列--1.4 字符替换(C语言)

2016-01-25 00:00 495 查看
题目:Write a method to replace all spaces in a string with '%20'.You may assume that the string has sufficient space at the end of the string to hold the additional characters,and that you are given the "true" length of the string.(Note:if implementing in Java,please use a character array so that you can perform this operation in place.)
EXAMPLE
Input: "Mr John Smith "
Output:"Mr%20John%Smith"
写一个方法用'%20'替换字符串中的所有空格。你需要确保字符串有足够的空间来存储额外的字符,你被给与字符串的真实长度。(注意:如果用Java实现,请使用character array这样你可以执行这个操作。)

####解题思路
首先按照题目意思是将空格替换为'%20',但按照题目给的示例字符串末尾的空格并没有转换成'%20'。我们这里还是按照将**==所有==**空格都转换成'%20'来处理。

在字符串处理中有个通用的方法是从字符串的末尾开始往回处理,我们这里就使用这个方法。

步骤:

获取字符串有效长度以及字符数组的总大小

计算字符串中空格的数目

计算替换空格后字符串的总长度并与字符数组大小比较。若超出字符数组大小则报错

从字符串末尾开始将字符搬移到新的位置,若遇空格则替换为'%20'

####代码实现
算法代码与测试程序如下:

#include <stdio.h>
#include <string.h>

int replaceSpace(char *str, int totalLen)
{
int newStrLen = 0;
int originStrLen = 0;
int spaceCount = 0;
int i;

originStrLen = strlen(str);

for (i = 0; i < originStrLen; i++)
{
if (str[i] == ' ')
{
spaceCount++;
}
}

newStrLen = originStrLen + spaceCount * 2;

if (newStrLen + 1 > totalLen)
return -1;
str[newStrLen] = '\0';
for (i = originStrLen - 1; i > 0; i--)
{
if (str[i] == ' ')
{
str[newStrLen - 1] = '0';
str[newStrLen - 2] = '2';
str[newStrLen - 3] = '%';
newStrLen = newStrLen - 3;
}
else
{
str[newStrLen - 1] = str[i];
newStrLen = newStrLen - 1;
}
}
return 0;
}

#define BUFLENS  50
int main(void)
{
char buf[BUFLENS] = "Mr John Smith   ";

printf("%s\n", buf);

replaceSpace(buf, BUFLENS);

printf("%s\n", buf);

getchar();
return 0;
}

####运行结果



文章转载自我的非鱼物语
本文固定链接为:http://linuxue.com/archives/20
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C CTCI 面试