URLify
#include <iostream>
#include <string>
using namespace std;
// Run-Time Check Failure #2 - S
// http://stackoverflow.com/questions/37128968/run-time-check-failure-2-s-visual-studio-c/37129017#37129017
// O(n) algorithm
// O(1) space
void replaceSpace(char *s, int length) {
int spaces = 0;
for (int i = 0; i < length; i++) {
if (s[i] == ' ') {
spaces++;
}
}
// new string that includes overwriting space, and two additional chars
int newLen = length + spaces * 2;
s[newLen] = '\0';
for (int i = length - 1; i >= 0; i--) {
if (s[i] == ' ') {
s[newLen - 1] = '0';
s[newLen - 2] = '2';
s[newLen - 3] = '%';
newLen -= 3;
}
else {
// working backwards, replace everything
s[newLen - 1] = s[i];
--newLen;
}
}
}
int main()
{
char test[] = "rep lace Spac e\0";
replaceSpace(test, 16);
cout << test << endl;
}Last updated