Is there no equivalent to the substr function in c++ in c???
Printable View
Is there no equivalent to the substr function in c++ in c???
You can use the sprintf function to simulate that.
I think he means strstr(), which finds a string within a string.
To extract a substring from a string, use strncpy, as in
strncpy( dest, &src[start], len );
dest[len] = '\0';
I took hk's reply in this manner:
Code:#include <stdio.h>
char *substr(char *dst, const char *src, int start, int len)
{
sprintf(dst, "%.*s", len, &src[start]);
return dst;
}
int main(void)
{
const char src[] = "Here is some text.";
char dst[sizeof src];
printf("dst = \"%s\"\n", substr(dst,src,5,7));
return 0;
}
/* my output
dst = "is some"
*/
There's no substr function in the C standard libraries. The standard libraries don't like using dynamic memory with strdup as the only exception I can think of. C++ has a bunch though, I don't know why but I suspect it's because they don't want to give people the burden of having to free memory themselves.
I wrote a substr function once which was supposed to be like the Perl substr but there were some limitations since I couldn't replace text on a string of unknown size so I had the function make a copy instead and that 0 and NULL is used to signal unused parameters.
substr("some string", 5, 0, NULL)Code:#include <stdlib.h>
char* substr (const char* string, int pos, int len, const char* replace)
{
char* substring;
int i;
int length;
if (string == NULL)
return NULL;
length = strlen(string);
if (pos < 0) {
pos = length + pos;
if (pos < 0) pos = 0;
}
else if (pos > length) pos = length;
if (len <= 0) {
len = length - pos + len;
if (len < 0) len = length - pos;
}
if (pos + len > length) len = length - pos;
if (replace != NULL) {
if ((substring = malloc(sizeof(*substring)*(length-len+strlen(replace)+1))) == NULL)
return NULL;
for (i = 0; i != pos; i++) substring[i] = string[i];
pos = pos + len;
for (len = 0; replace[len]; i++, len++) substring[i] = replace[len];
for (; string[pos]; pos++, i++) substring[i] = string[pos];
substring[i] = '\0';
}
else {
if ((substring = malloc(sizeof(*substring)*(len+1))) == NULL)
return NULL;
len += pos;
for (i = 0; pos != len; i++, pos++)
substring[i] = string[pos];
substring[i] = '\0';
}
return substring;
}
returns "string"
substr("some string", -5, 3, NULL)
returns "str"
substr("some string", 4, 0, "thing")
returns "something"
free() needs to be called on the string returned after it's use.