0

I have a message which I receive in the rmsg variable. If the first character in this buffer is '1', I want to remove this char and send the rest of the message.

So is there any way to do something like this:

if(rmsg[0]=='1')

//remove the first character in rmsg
strncpy(newbuf,rmsg,rmsglen)

If this is not the right direction could anyone show me how?

Peter Brittain
  • 13,489
  • 3
  • 41
  • 57

3 Answers3

3

I suppose it is what you want to achieve in this case:

if (rmsg[0] == '1') 
    memmove(rmsg, rmsg+1, strlen(rmsg));

Here, after using memmove() function like I posted above, your rmsg string will contain its previous content without first char (which is == '1'), so now you can just send it easily wherever you want.

Live demo: http://ideone.com/1dJjAn
More about memmove() func: http://www.cplusplus.com/reference/cstring/memmove/

mtszkw
  • 2,717
  • 2
  • 17
  • 31
2

You can use the second char as base address for sending and decrease the length by 1:

   if (rmsglen > 0 && rmsg[0]=='1')
      send (&rmsg[1], rmsglen-1);
thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
2

If you want to copy the string to new string expect the first character you can do something like this -

char rmsg[]="1 I can go";
char *newbuf;
newbuf=malloc(strlen(msg));
if(rmsg[0]=='1')
{
    strncpy(newbuf,&rmsg[1],rmsglen-1);  
}
free(newbuf);

Small example -https://ideone.com/IotuBy

ameyCU
  • 16,489
  • 2
  • 26
  • 41
  • 1
    A couple of thoughts: The `+1` isn't needed since the copied string will be shorter and there's thus enough space for the trailing NULL. Why do you think there's a space after the `1`? And why do you think OP want's to skip it, he doesn't say so? Also, [avoid `strcpy`](http://stackoverflow.com/questions/1258550/why-should-you-use-strncpy-instead-of-strcpy), the length is already known (`rmsglen`). – DarkDust Aug 27 '15 at 12:52
  • @DarkDust The space after `1` was just my thought in case if it is there. And about `+1` yes that was not needed. And I didn't notice `rmsglen` thus didn't took that in account. But thanks for your input I edited my answer. – ameyCU Aug 27 '15 at 12:58