顿搜
飞过闲红千叶,夕岸在哪
类目归类
Write a method to replace all spaces in a string with %20. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.
You code should also return the new length of the string after replacement.
Given "Mr John Smith", length = 13.
The string after replacement should be "Mr%20John%20Smith", you need to change the string in-place and return the new length 17.
int replaceBlank(char string[], int length)
{
if (string == NULL) {
return 0;
}
int spaceCount = 0;
for (int i = 0; i < length; i++) {
if (string[i] == ' ') {
spaceCount++;
}
}
int len = length + (spaceCount << 1);
int right = len - 1;
for (int i = length - 1; i >= 0; i--) {
if (string[i] != ' ') {
string[right--] = string[i];
}
else {
string[right--] = '0';
string[right--] = '2';
string[right--] = '%';
}
}
return len;
}#include <stdio.h>
using namespace std;
class LintCode0212 {
public:
int replaceBlank(char string[], int length)
{
if (string == NULL) {
return 0;
}
int spaceCount = 0;
for (int i = 0; i < length; i++) {
if (string[i] == ' ') {
spaceCount++;
}
}
int len = length + (spaceCount << 1);
int right = len - 1;
for (int i = length - 1; i >= 0; i--) {
if (string[i] != ' ') {
string[right--] = string[i];
}
else {
string[right--] = '0';
string[right--] = '2';
string[right--] = '%';
}
}
return len;
}
};
int main()
{
LintCode0212 lintcode;
char string[] = { 'M', 'r', ' ', 'J', 'o', 'h', 'n', ' ', 'S', 'm', 'i', 't', 'h', '\0' };
printf("%d", lintcode.replaceBlank(string, 13));
return 0;
}