|
From: Per W. <pw...@ia...> - 2002-12-29 03:51:02
|
/* Note 1 - remember to free() string after use. */
/* Note 2 - start is zero-relative. */
char* substr(const char* s,size_t start,size_t len) {
char *p;
size_t slen;
if (s == NULL) return NULL;
slen = strlen(s);
if (start >= slen) {
start = slen;
len = 0;
}
if (start + len > slen) len = slen - start;
p = (char*)malloc((len+1)*sizeof(char));
strncpy(p,s+start,len);
p[len] = '\0';
return p;
}
/Per W
On Sat, 28 Dec 2002, Danny Roelofs wrote:
> Hi,
>
> Another problem to solve.. i wish to make a routine which gives me a substring or trimmed down on the following
> conditions that i can start from anypoint in the string untill the offset is reached. so for example
>
> mytext = "this is a test";
> result = substring(mytext,6,2);
>
> result would now have to contain the 2nd word "is"...
>
> thats my goal.. i couldn't figure out a single function for it, if someone knows a solution.. would be great..
>
> or if you know how to "build" a new string, which in my thought has to go like this:
>
> mytext = "this is a test";
>
> mytext ++ ( 5 times) to set a pointer somehow to the 5th char in the string.
>
> subtext = subtext + pointer to mytext
>
> mytext ++ (1 time) to go to the next char in the string
>
> subtext = subtext + point to mytext
>
> which will give me "is" in the subtext...
>
>
>
> I could find decent material while searching the internet.. normaly, in my pas i always had the benefit of functions called substr
> and trimstr but they dont exist as far as i know for cpp..
>
>
> thanks for any help..
>
> danny
>
>
|