Does C have the equivalent of the C++ substring function?

fgs3124
fgs3124 used Ask the Experts™
on

I am writing a C program and need to use the equivalent of the C++ substring function to return the 1st 10 characters of a string.  Does C have something similar or has anyone had to write their own function?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
if you want the first 10 characters, you could do the following:

---
char strSource[] = "This is the source string";
char strDest[11];

strncpy(strDest, strSource, 10);
strDest[10] = 0;

printf("The first 10 characters are : %s\n", strDest);
---
Also, here is a quick implementation of a substr function.  Keep in mind that you will need to free the pointer to the resulting string when you are done using it.


char * substr(char * strSource, int start, int length) {

   char * strResult;
 
   strResult = (char *) malloc((sizeof(char) * length) + 1);
   strncpy(strResult,strSource + start, length);
   strResult[length] = 0;
   
   return strResult;
   
}

Commented:
strncpy(stringyouwant, sourcestring, 10)
char *stringyouwant;
char *sourcestring;

Commented:
3 things too all those who asnwered this question:

A.YOU ARE NOT SUPPOSED TO SOLVE THE WHOLE PROBLEM FOR HIM!!!!

B.the solutions you give him forget one thing-he is supposed to return the first 10 chars of a string.if you do this by malloc,you actually need to get the length of the string etc.,and its even more comlicated than what the first answer was like.

C.i think the easiest thing is to do this by one of two ways:the first is with a recursive function.
the second is the easiest one(in my oppinion):simply call a function that takes the char from the last place taken+1(its easy,and i wont show it).
this means that you call a function that takes the first char,and then calls the function to return the second char and so on.

yair

Author

Commented:
I appreciate your help.  Thank you for your generousity.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial