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

Subscript of string

Status
Not open for further replies.

LotusE

Programmer
Nov 22, 2002
25
BE
Hi,

I'm fairly new to C, but I need to program a barcode scanner.

I need a function that allows me to substract a small string from a larger string, but I want to be able to give the starting and end position.

For example:

String= "abcdefgh"

I want to able to get all the letters from position 2 to 5 in the string, for example, so it will give me "bcde".

Is this possible, because I can't find a standard function in C that will allow me to do this.

Thanks in advance for your reply!

Cheers

Steve
 
I meant of course "Substring" of a string. Not fully awake yet, I think.. :)
 
One way :

Code:
int iParentIdx;
int iSubStrIdx;
char szSubStr[16];
char* szParentStr = "abcdefgh";
memset(szSubStr, '\0', sizeof(szSubStr));
iSubStrIdx = 0;
for (iParentIdx = 2; iParentIdx <= 5; iParentIdx++) {
  szSubStr[iSubStrIdx++] = szParentStr[iParentIdx];
}



--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Or perhaps memcpy() :

Code:
char szParentStr[]= "abcdefgh";
char szSubStr[16];
memset(szSubStr, '\0', sizeof(szSubStr));
memcpy (szSubStr, &szParentStr[2], 3);

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
I'd prefer strncpy(). That way you don't need the memset() to set szSubStr to all NULLs.
 
That's only if your string completely fills the buffer, but in that case, you should use a bigger char* buffer anyways.
 
It doesn't null terminate the string in a particularly relevant case.
Code:
#include <stdio.h>
#include <string.h>

int main(void)
{
   char a[] = "XXXXXXXXXXXXX", b[] = "hello";
   strncpy(a, b, 4);
   puts(a);
   return 0;
}

/* my output
hellXXXXXXXXX
*/
 
Oh crap, that'll teach me for posting when I'm in a hurry...
 
Thanks guys for all your answers!

Cheers

LotusE
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top