Link to home
Start Free TrialLog in
Avatar of fgs3124
fgs3124

asked on

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


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?
Avatar of BlackDiamond
BlackDiamond

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);
---
ASKER CERTIFIED SOLUTION
Avatar of BlackDiamond
BlackDiamond

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
strncpy(stringyouwant, sourcestring, 10)
char *stringyouwant;
char *sourcestring;
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

Avatar of fgs3124

ASKER

I appreciate your help.  Thank you for your generousity.