Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

implementing substring in C

Status
Not open for further replies.

anand102

Programmer
Aug 2, 2001
11
US
hi,


i want to implement substr function in C for getting substring. if somebody has already done so then pls
give me your code.


thanks
 
this is a function which return -1 if substring is not find and its position if yes:
int find(char*x, char*y)
{
int max_search = strlen(x) - strlen(y);
int i;
int len_earch = strlen(y);
if(max_search<0) return -1;
for(i=0;i<max_search;i++)
{
if(!strncmp(x[i],y,len_search)return i;
}
return -1;
}

you'll use it like:
char* a = &quot;hello word&quot;;
char* b = &quot;hello&quot;;
int pos = find(a,b);
John Fill
1c.bmp


ivfmd@mail.md
 
anand102,

In case you're not trying to implement 'substr' as some sort of training assignment:

The C run-time library has a function that does this for you - strstr.

Regards
 
actually i am looking for version of tpye :


substr(str, pos1,pos1)

which return me substring between pos1 and pos1 in orinignal string str.


thnaks
 
just use strncpy.

char* substr( char str, pos1, pos2)
{
char* x = malloc(pos2-pos1+1);
strncpy(x,str[pos1],pos2-pos1);
} John Fill
1c.bmp


ivfmd@mail.md
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top