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

Cracking The Coding Interview 3rd -- 1.4

2014-01-13 12:53 423 查看
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).


Solution: A common approach in string manipulation problems is to edit the string starting from the end and work backwards. For this problem, we work through two scan approach. In the first scan, we count how many spaces there are in the
string. This is used to compute how long the final string should be. In the second pass, which is done in reverse order, we actually edit the string.

Header file

#ifndef __QUESTION_1_4_H_CHONG__
#define __QUESTION_1_4_H_CHONG__

class Question1_4 {
public:
void replaceSpaces(char str[], int length);
int run();
};

#endif // __QUESTION_1_4_H_CHONG__


Source file
#include "stdafx.h"
#include <iostream>
#include "Question1_4.h"

using namespace std;

void Question1_4::replaceSpaces(char str[], int length)
{
int numOfSpaces = 0;
for (int i=0; i<length; i++) {
if (str[i]==' ') {
numOfSpaces++;
}
}

int trueLength = length + 2*numOfSpaces;
for (int i=length-1, j=trueLength-1; i>=0; i--, j--) {
if (str[i]!=' ') {
str[j] = str[i];
}
else {
str[j-2] = '%';
str[j-1] = '2';
str[j] = '0';
j = j - 2;
}
}
}

int Question1_4::run()
{
char str[100] = "Hello Chong!";
int length = 12;
replaceSpaces(str, length);
cout << str << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息