开发者

get substring in c [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜