extract substring from string in C
hallo,is there no function in C (like substr in PHP) to extract a substring from one string into another.for instance if I have
char string1[10]; if string1 = '12345678' how can i store '34567' into another string(in PHP substring(string1,3,4) would have worked.) thanks |
Of course you can do this in C. Have a look at the following link where you will find all standard C string functions:
http://www.cppreference.com/stdstring/index.html For your purpose you should use the function 'strncpy' Here an example: Code:
#include <string.h> |
thanks,that worked!although i must confess i'm a bit rusty on the whole C pointer thing.I'll just use it for now,figure out the details later..
|
You have to put '\0' at the end of the string...
|
Quote:
Code:
#include <string.h> |
You also have to free any allocated memory, including if you use strdup().
Here's another take on what otherwise should have been a simple exercise: PHP Code:
|
//simple program to extract substring from a given string
#include<stdio.h> #include<conio.h> #include<string.h> void extract(char *,char *,char *,int,int); void main() { char s[50]="working with strings is fun"; char t[50]; char d[50]; int pos,len; printf("enter the position and length to be extracted= "); scanf("%d%d",&pos,&len); printf("\n\n"); extract(s,t,d,pos,len); puts(d); getch(); } void extract(char *s,char *t,char *d,int pos,int len) { s=s+(pos-1); t=s+len; while(s!=t) { *d=*s; s++; d++; } *d='\0'; } email id:-aryagaurav_dce_cs@yahoo.co.in |
All times are GMT -5. The time now is 04:37 PM. |