- 论坛徽章:
- 0
|
递归嘛- #include <stdio.h>
- char* trim(char*);
- char* add_to_head(char head, char* str);
- int main(int argc, char** argv)
- {
- if(argc != 2)
- {
- printf("Args not correctly supplied\nUsage:trim string\n");
- exit(1);
- }
- char* res = trim(argv[1]);
- printf("Trim of %s is:%s\n", argv[1], res);
- return 0;
- }
- char* trim(char* message)
- {
- char *next = message + 1;
- if(*message == '\0')
- {
- return "";
- }
- else if(*message == ' ')
- {
- return trim(next);
- }
- else
- {
- return add_to_head(*message,trim(next));
- }
- }
- /*
- *Add a character to the head of a String
- */
- char* add_to_head(char head, char* str)
- {
- char* local = (char*)malloc(sizeof(char*));
- char* p = str;
- *local = head;
- int i;
- for(i = 0; *p != '\0'; p++, i++)
- {
- local[i+1] = *p;
- }
- return local;
- }
复制代码 |
|