Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implement the method of replacing all the spaces in the string with substring "%20"
- char* replace_spaces(const char *s)
- {
- const char SPACE = ' ';
- const char REPLACEMENT[] = "%20";
- unsigned int numOfSpaces = 0;
- for(int i = 0; i < strlen(s); i++)
- {
- if(s[i] == SPACE)
- {
- numOfSpaces++;
- }
- }
- // we have found number of spaces in the string
- // it helps us to define the exact size of modified string
- char* modifiedString = new char[strlen(s) - numOfSpaces + numOfSpaces*strlen(REPLACEMENT) + 1];
- modifiedString[strlen(s) - numOfSpaces + numOfSpaces*strlen(REPLACEMENT)] = '\0';
- for(int sourceStrIdx = 0, modifiedStrIdx = 0; sourceStrIdx < strlen(s); sourceStrIdx++)
- {
- if(s[sourceStrIdx] != SPACE)
- {
- modifiedString[modifiedStrIdx] = s[sourceStrIdx];
- modifiedStrIdx++;
- }
- else
- {
- for(int k = 0; k < strlen(REPLACEMENT); k++)
- {
- modifiedString[modifiedStrIdx] = REPLACEMENT[k];
- modifiedStrIdx++;
- }
- }
- }
- return modifiedString;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement