调用代码
NSString *a = @"abc";
NSString *b = @"def";
//手写的字符串的拼接
char *c = str_cat([a UTF8String], [b UTF8String]);
实现代码
char *str_cat(const char *str1, const char *str2){
int len1 = 0;
int len2 = 0;
for (len1 = 0; *(str1+len1) != '\0'; len1++){} //获取str1长度
for (len2 = 0; *(str2+len2) != '\0'; len2++){} //获取str2长度
char *ret = (char *)malloc(sizeof(char)*(len1+len2+1)); //申请动态空间
/*内存赋值*/
int i;
for (i=0; i<len1; i++){
*(ret+i) = *(str1+i);
}
for (i=0; i<len2; i++){
*(ret+len1+i) = *(str2+i);
}
*(ret+len1+len2) = '\0';
return ret;
}
网友评论