Topic:
There is a string beginning or ending with n spaces ("ABCDEFGDDDD") to remove the front and back spaces and return a new string.
1 //string two-block model2 intTRIMSPACESTR (Char*p,Char*buf)3 {4 intRV =0;5 Char*str =p;6 inti =0;//Search pointer variables, starting at the head of the string7 intj = strlen (str)-1;//search for pointer variables, starting at the end of the string8 intLen =0;//valid length of string9 Ten if(Str==null | | buf==NULL) One { ARV =-1; -printf"Function trimspacestr () Check (Str==null | | buf==null) Error:%d", RV); - returnRV; the } - - while(Isspace (Str[i]) && i<j) - { +i++; - } + A while(Isspace (Str[j]) && j>=0) at { -j--; - } - -Len = j-i+1; - instrncpy (BUF, str+I, Len); - toBuf[len] =' /'; + returnRV; - } the intMain () * { $ intRET =0;Panax Notoginseng - //allocated a memory space in the stack and copied a copy of the the CharStr[] ="abcdefgdddd"; + A Charp1[ -]; the +RET =trimspacestr (str, p1); - $ if(Ret! =0) $ { -printf"Function delspace () Error:%d \ n", ret); - } the -printf"After Delete Space:%s\n", p1);Wuyi the return 0; -}
Analysis:First look at the functionint trimspacestr (char *p, char *buf), allocating memory in the main function, passing in the called function, preferably const in front of Char *p, prevents accidental modification of the source string
Then look at int main (), copy the string into the memory block temporarily assigned to the first address in Str, char str[] = "abcdefgdddd", the same as char p1[], will two into functions as arguments < Span style= "color: #008080;" >< Span style= "color: #800080;" > /span>
< Span style= "color: #0000ff;" > note: < Span style= "color: #008080;" >< Span style= "color: #800080;" > "ABCDEFGDDDD", the *p is not modified in the function, the string is in the constant area
Summarize:
1. The string can be in the stack area str[]= "", heap area char *p = malloc, and a constant area to allocate memory char *p = "", Be careful!!
2. Do not easily modify the contents of the memory block from other places, and really want to modify the new self to open up a piece of memory!
String--two-block model analysis