How would you get a string of characters from an array in c?

Viewed 72

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.

2 Answers

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

char array[15] = "asdfghjkbruhqw";
char dest[10] = "";
strncpy(dest, &arr[9], 3);

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 */
Related