Saturday, July 7, 2007

Implement the substr() function in C.

Here is a C program which implements the substr() function in C.


int main()
{
char str1[] = "India";
char str2[25];

substr(str2, str1, 1, 3);
printf("\nstr2 : [%s]", str2);
return(0);
}

substr(char *dest, char *src, int position, int length)
{
dest[0]='\0';
strncat(dest, (src + position), length);
}




Here is another C program to do the same...


#include
#include

void mySubstr(char *dest, char *src, int position, int length);

int main()
{
char subStr[100];
char str[]="My Name Is Sweet";

mySubstr(subStr, str, 1, 5);
printf("\nstr = [%s]"
"\nsubStr = [%s]\n\n",
str, subStr);
getch();
return(0);
}

void mySubstr(char *dest, char *src, int position, int length)
{
while(length > 0)
{
*dest = *(src+position);
dest++;
src++;
length--;
}
}

7 comments:

Anonymous said...

The implementation is good, but it doesn't take care of null character in destination string.

binu said...

void mySubstr(char *dest, char *src, int position, int length)
{
while(length > 0)
{
*dest = *(src+position);
dest++;
src++;
length--;
}
*dest='\0';
}
please assign a termination character to the destination string ,it works well

Anonymous said...

wat will happen if the position exceeds the string1 or position + lenght exceeds size of string1

Acalb said...

substr function does not take 4 arguments. It should be 5 which are
char des[], char src[], int start, int end, int dest_len

so,

substr(char dest[], char src[], int start, int end, int dest_len);

Thanks for explanation.

Anonymous said...

Can you tell us more about this? I'd care to find out some additional information.

Look at my website: diets that work fast for women

Anonymous said...

Wow, superb blog layout! How long have you been blogging for?
you make blogging look easy. The overall look of your site is great, let alone the content!


Here is my blog ... height to waist ratio

Anonymous said...

Wow, incredible weblog format! How long have you ever been running
a blog for? you make blogging glance easy. The overall look of your website
is great, let alone the content material!

My web site ... how much should i weigh chart