Q. 1: Implement the following function:
surround(char * str, char c)
The first argument is a pointer to a string, whereas the second argument is a
character. When the function returns, the string pointed to by str should be
surrounded by the character in variable c. For instance, if str points to “this”,
and c is ‘X’, then after the function returns, str should point to “XthisX”.
1
Expert's answer
2017-06-19T09:55:10-0400
void surround(char * str, char c) { /* step 1 - find end of str */ char* s = str; while(*s) { s++; }
/* extend str by 2 characters */ s+=2; /* make end symbol for extended str */ *s = 0; s--; /* put ending surrounding symbol */ *s = c; s--; /* shift right original str string by one position */ while(s>str) { *s = *(s-1); s--; } /* put beginning surrounding symbol */ *str = c; }
Comments
Leave a comment