开发者

Take substring of a string in c

开发者 https://www.devze.com 2022-12-17 09:59 出处:网络
I want to take a substring of the string buffer by doing something like the below.I don\'t know if it\'s possible (I\'ve been coding in C for all of about 6 hrs now, but feel free to be as technical a

I want to take a substring of the string buffer by doing something like the below. I don't know if it's possible (I've been coding in C for all of about 6 hrs now, but feel free to be as technical as you like, I think I can handle it (though I may be wrong))

Edit: I want to take a substring of buffer from the beginning of buffer to 开发者_JAVA百科the first space.

if (buffer[c] == ' ') {
    in_addr_t addr;
    char *ptr = *buffer;
    if(inet_aton("*ptr to *ptr+c", &addr)!=0){
           //do stuff;
    }
}


I have to make one assumption since there are a number of problems with the code: Assuming that buffer[c] is the first character before the inet address

if (buffer[c] == ' ')
{
     in_addr_t addr
     if (inet_aton(&buffer[c+1], &addr))
          // do stuff
}

Note:

  • inet_aton is deprecated since it does not support ipv6. Use int inet_pton(int af, const char *src, void *dst); for forward compatibility.

-- Edit --
To take the substring from the beginning of buffer to (but not including) buffer[c], any of these will work:

1

char buf2 [MAX];
strncpy (buf2, buffer, c);
buf2 [c] = '\000';

2

char buf2 [MAX];
sprintf (buf2, "%.*s", c, buffer);

3

char buf2 [MAX];
int  j;
for (j = 0;  j < c;  ++j)
    buf2 [j] = buffer [j];
buf2 [c] = '\000';


If you can modify the original buffer, you could just ignore your ptr variable and do:

if (buffer[c] == ' ') {
    in_addr_t addr;
    buffer[c] = '\0';
    if (inet_aton(buffer, &addr) != 0) {
        // do stuff;
    }
}

If you can't modify the original buffer, just use strncpy() to copy the part you care about out into a new buffer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号