I already have a function to get substring of a string
void subString(char* buffer, char* s开发者_开发技巧tr, int start, int length)
{
int i, x = 0;
int end=start+length;
for(i = start ; i <= end; i++)
buffer[x++] = str[i];
buffer[x] = '\0';
//return temp;
}
new string is stored in buffer
but I prefer the function likes
char * subString(char* str, int start, int length)
{
//.......
}
it will automatically returns the string pointer that has been alloced memory.
Welcome any comment
What's wrong with just adding the malloc into your new function and leaving the rest the same?
#include<stdlib.h>
char * subString(char* str, int start, int length) {
char *newString = (char *)malloc(length * sizeof(char));
int i, x = 0;
int end=start+length;
for(i = start ; i <= end; i++)
newString[x++] = str[i];
newString[x] = '\0';
return newString;
}
Since you are treating strings as simple character arrays, why don't you simply use plain old strncpy
?
strncpy(dest, str+offset, len);
精彩评论