Last active
August 29, 2015 13:57
-
-
Save lynxerzhang/9525274 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
char* concatstr(char*, char*); | |
int strlen(char*); | |
int strend(char*, char*); | |
//K&R的c语言指针章节练习题 | |
int main(void) | |
{ | |
char *a = "hello1"; | |
char *b = "world2"; | |
char *c = concatstr(a, b); | |
printf("%s\n", c); | |
char *d = "hello"; | |
char *e = "llo"; | |
int result = strend(d, e); | |
printf("%d", result); | |
return(EXIT_SUCCESS); | |
} | |
//检查end字符数组是否位于main字符数组末端 | |
int strend(char *main, char *end){ | |
char *result = main; | |
char *last = end; | |
int endlen = strlen(last); | |
int index = 0, found = 0; | |
while(*result){ | |
if(*result == *last){ | |
last++; | |
if(++index == endlen){ | |
found = 1; | |
} | |
} | |
else{ | |
index = 0; | |
found = 0; | |
} | |
result++; | |
} | |
return found; | |
} | |
//连接指定字符数组, 并返回一个新的字符数组 | |
char* concatstr(char *a, char *b){ | |
char *c = malloc(strlen(a) + strlen(b) + 1);//new 'a new string' | |
char *d = c; | |
if(d){ | |
while(*a){ | |
*d = *a; | |
d++; | |
a++; | |
} | |
while(*d++ = *b++); | |
*d = '\0';// | |
return c; | |
} | |
return NULL; | |
} | |
//获取字符数组长度 | |
int strlen(char *c){ | |
int len = 0; | |
char *result = c; | |
while(*result++){ | |
len++; | |
} | |
return len; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment