2

I am trying to parse data from the user. I need to get a certain number from the user.

And I do not mean like with strstr(). I mean more like characters 9-12 in an array.

For example:

char array[15] = "asdfghjkbruhqw";
                          ^--^

I cannot figure out a way to do this. Any help would be appreciated.

Finxx
  • 61
  • 1
  • 7

2 Answers2

4

Use strcnpcy, in the second parameter you pass the starting position:

char array[15] = "asdfghjkbruhqw";
char dest[10] = "";
strncpy(dest, &arr[9], 3);
vmp
  • 2,370
  • 1
  • 13
  • 17
2

A "string" in C behaves just like any other array, so in order to retrieve a subset of the string you must manually copy each element from a source to destination array. There are a few ways of going about this:

Simplest option

char my_source_array[15] = "asdfghjkbruhqw";
char my_dest_array[5];

int offset_start = 8; /* index of "b" in "bruh" */
int num_chars = 4;

for (int i = 0; i < num_chars+1; ++i) {
  my_dest_array[i] = my_source_array[offset_start+i];
}
my_dest_array[num_chars] = 0; /* don't forget to null-terminate */

Slightly more advanced

char my_source_array[15] = "asdfghjkbruhqw";
char my_dest_array[5];

int offset_start = 8; /* index of "b" in "bruh" */
int num_chars = 4; /* number of chars in "bruh" */
memcpy(my_dest_array, my_source_array+offset_start, num_chars*sizeof(char));
my_dest_array[num_chars] = 0; /* don't forget to null-terminate */
Jacob Faib
  • 1,062
  • 7
  • 22
  • 2
    May want to *nul-terminate* the `my_dest_array`, e.g. `my_dest_array[num_chars] = 0;` So that `my_dest_array` can be treated as a string. – David C. Rankin Jan 26 '21 at 00:30