-
Substring of a string
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
-
One solution would be to use strncpy. You can specify the amount of characters to copy, and when you specify the source string, calculate the starting offset.
For example, for position 2 to 5, you'd use:
Code:
strncpy(dst, src + 1, 4);
We specify + 1 for position 2 because C arrays are zero based. The 4 is the number of characters between 2 and 5.
Remember that strncpy will NOT null terminate the string for you (unless you copy to the end of src (not in this case)), so you'd need an additional: afterward.
I'll leave it as an exercise for you to produce a function to do this. Example declaration:
Code:
void slice(char *dst, char *src, int start, int finish)
{
}
Of course dst will need to point to something capable of holding at least (finish - start + 2) elements.
-
Or you can use a for loop:
Code:
int x;
for(x = 1; x < 5; x ++) {
printf("%c", array[x]); /* or assign this value somewhere else */
}
Or you could use printf():
Code:
/* print a maximum of 4 chars, starting with array[1] */
printf("%.*s", 4, array+1);
Note: array+1 is the same as &array[1].