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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

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

Status
Not open for further replies.

fgs3124

IS-IT--Management
Mar 6, 2002
8
US

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?
 
Use the strncpy function which allows you to specify how many bytes to copy.

To copy the 1st 10 bytes use the following.....
strncpy(outbuff,inbuff,10); /* Copy 10 bytes */
outbuff[10]=0x00; /* Terminate string */

To copy 10 bytes starting at the 5th byte use the following...

strncpy(outbuff,inbuff+3,10);
outbuff[10]=0x00;

Cheers - Gavin
 
first 10 char:
sprintf(outbuff,"%.10s",inbuff);
10 char starting by 3 char 0f inbuff:
sprintf(outbuff,"%.10s",&inbuff[3]);
or if pointers:
sprintf(outbuff,"%.10s",inbuff+3);
-----------
when they don't ask you anymore, where they are come from, and they don't tell you anymore, where they go ... you'r getting older !
 
Just for information - although its probably not so important these days with fast processors...printf and all its variants (sprintf, fprintf etc) is very inefficient. strcpy, strncpy or memcpy are far more efficient in operation.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top