Daily Question 11: replace spaces in strings, and 11 replace string Spaces
Replace all spaces in a string with a specified character or string. It is naturally easy to replace the character with a character, but when you replace the character with a string, if you still traverse from the past to the next, if you encounter a specified character, you can remove all the subsequent characters from enough space. When there are many spaces in the string, repeated characters will cause performance loss. But what if it is traversing from the back? You can traverse the original string to obtain the number of spaces in the string, and then calculate the space required, assuming that the buffer where the original string is located has enough space (otherwise, you can create a new buffer and traverse it from the back to the back. Here we will do this without creating a buffer ), then the final position of each character can be calculated. In the algorithm, a pointer q can be used to point to the position of the last character (that is, the string Terminator) of the replaced string, the pointer p points to the last character (string Terminator) of the original string, and then the two pointers traverse forward. If the character p points to is a space, then, the replacement string will be filled from the back to the position pointed to by q (in this process, p does not move, q continues forward, and the computation after the first traversal ensures that q does not catch up with p ), then the two pointers continue to traverse forward. In this way, an O (N) algorithm is obtained.
#include "stdafx.h"#include <iostream>using namespace std;const int bufsize = 1024;void Replace(char** str, char target_char,const char* replace_str){ int replace_str_len = strlen(replace_str); char* p = *str; int target_char_fre = 0; int str_len = 0; while(*p) { if(*p == target_char) ++target_char_fre; ++str_len; ++p; } int extend_count = target_char_fre * (replace_str_len - 1); char * q = p + extend_count; int j = 0; while(j <= str_len) { if(*p != target_char) *q-- = *p--; else { const char* r = &replace_str[replace_str_len - 1]; int i = 0; while(i < replace_str_len) { *q-- = *r--; ++i; } --p; } ++j; }}int _tmain(int argc, _TCHAR* argv[]){ char * str = new char[bufsize]; strcpy(str," wo shi zhong guo ren!"); Replace(&str,' ',"%20"); cout<<str<<endl; return 0;}
If you cannot get through in one direction, try another direction! This method can also be used in similar scenarios such as array insertion.