S function match all characters to be printed from among ch1 to ch2 and ch1 return address.


. 1
char * match ( char * S, char CHl, char CH2) { 2 int len = 0 ; . 3 int m = 0 ; . 4 int I = 0 ; . 5 the while (S [len]) { . 6 len ++ ; . 7 } . 8 . 9 char t [ 2 * len + . 1 ]; // string s are full to prevent overflow leading to t 10 the while (I <( 2 * len + . 1 )) { . 11 t [I] = '\ 0 ' ; 12 is I ++ ; 13 is } // Initialization 14 I = 0 ; 15 the while (! S [I] = ch1 && s [I]) { 16 I ++ ; . 17 } // find ch1 position in s 18 is int K = I; . 19 IF (I < len) { 20 is do { 21 is T [m] = S [I]; 22 is m ++ ; 23 is I ++ ; 24 } the while (S [I] = CH2 &&! S [I]); // ch1 character from the beginning of the stores in t 25 IF (I < len) { 26 is t [m] = S [I]; 27 m ++ ; 28 } // if present ch2, the ch2 stored in t 29 t [m] = ' \ n- ' ; 30 the while ( s [K]) { 31 is m ++ ; 32 T [m] = s [K]; 33 is K ++ ; 34 is } // stored in the address in s ch1 is 35 36 } the else 37 [ { 38 is T [ 0 ] = ' \ n- '; 39 }

// string has been improved so far t
40 I = 0 ; 41 is the while (t [I]) { 42 is s [I] = t [I]; 43 is I ++ ; 44 is } // will replace t s 45 S [I] = ' \ 0 ' ; // prevent T <S 46 is 47 return S; 48 }

When the idea to write this function is actually very clear, but encountered a bunch of questions after the finish

1. Initially I was directly return t; however garbled when printf returns to the main post, that is behind the query data on the stack, the function of the variable as a function once the body will be released,

   At this address output of the variable will be a mess of things, the current solution I can think of is to use the s t back;

2. In the PTA char * t [2 * len + 1] = { '\ 0'}; not compile, but can by the devc ++, if t is not initialized, it will lead to a multi-copy replication time t s Some things should not be there, so I used the most primitive of the while loop;

3.s [i] = '\ 0'; easily overlooked, which is to prevent a string of t s shorter in length than the original length, so that there t is copied after the character.

Guess you like

Origin www.cnblogs.com/chenshipeople/p/12290208.html