Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C setting string equal to substring

In C, If I have:

char *reg = "[R5]";

and I want

char *reg_alt = "R5" (equal to the same thing, but without the brackets), how do I do this?

I tried

*char reg_alt = reg[1:2];

but this doesn't work.

like image 671
Austin Avatar asked Mar 14 '16 03:03

Austin


2 Answers

There is no built-in syntax for dealing with substrings like that, so you need to copy the content manually:

char res[3];
memcpy(res, &reg[1], 2);
res[2] = '\0';
like image 113
Sergey Kalinichenko Avatar answered Oct 04 '22 01:10

Sergey Kalinichenko


I suggest you need to read a basic text on C, rather than assuming techniques from other languages will just work.

First, char *reg = "[R5]"; is not a string. It is a pointer, that is initialised to point to (i.e. its value is the address of) the first character of a string literal ("[R5]").

Second, reg_alt is also a pointer, not a string. Assigning to it will contain an address of something. Strings are not first class citizens in C, so the assignment operator doesn't work with them.

Third, 1:2 does not specify a range - it is actually more invalid syntax. Yes, I know other languages do. But not C. Hence my comment that you cannot assume C will allow things it the way that other languages do.

If you want to obtain a substring from another string, there are various ways. For example;

  char substring[3];
  const char *reg = "[R5]";    /* const since the string literal should not be modified */

  strncpy(substring, &reg[1], 2);     /* copy 2 characters, starting at reg[1], to substring */
  substring[2] = '\0';     /*  terminate substring */

  printf("%s\n", substring);

strncpy() is declared in standard header <string.h>. The termination of the substring is needed, since printf() %s format looks for a zero character to mark the end.

like image 22
Peter Avatar answered Oct 04 '22 03:10

Peter