[英]Take substring of a string in c
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))
我不知道是否可能(我现在已经用C进行了大约6个小时的编码,但是随时随心所欲,我想我可以处理(尽管我可能错了))
Edit: I want to take a substring of buffer from the beginning of buffer to 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 我必须做一个假设,因为代码存在许多问题:假设buffer [c]是inet地址之前的第一个字符
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. inet_aton
,因为它不支持ipv6。 Use int inet_pton(int af, const char *src, void *dst);
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: 要将子串从
buffer
的开头带到(但不包括) buffer[c]
,以下任何一种都可以工作:
char buf2 [MAX];
strncpy (buf2, buffer, c);
buf2 [c] = '\000';
char buf2 [MAX];
sprintf (buf2, "%.*s", c, buffer);
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: 如果可以修改原始缓冲区,则可以忽略
ptr
变量并执行以下操作:
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. 如果您不能修改原始缓冲区,只需使用
strncpy()
将您关心的部分复制到新缓冲区中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.