开发者

get substring in c [closed]

开发者 https://www.devze.com 2023-03-21 09:54 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
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

精彩评论

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