我有一个长度为32的字符数组,并希望从中提取某些字符。例如
111111000000000000000000111111 <32个字符
我想要0-6的字符,应该是111111
或者甚至取26-31个字符,它应该是111111
char check_type[32];上面是我如何声明的。
我希望能够做的是定义一个函数或使用一个函数,它接受开始位置和结束字符。
我已经看过很多方法,比如使用strncpy和strcpy,但还没有找到任何方法。
发布于 2011-12-26 06:36:18
使用memcpy。
// Stores s[from..to) in sub.
// The caller is responsible for memory allocation.
void extract_substr(char const *s, char *sub, size_t from, size_t to)
{
size_t sublen = to - from;
memcpy(sub, s + from, sublen);
sub[sublen] = '\0';
}发布于 2011-12-26 06:43:58
我会简单地包装strncpy
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Creates a sub-string of range [start, end], return value must be freed */
char *substr(char *src, size_t start, size_t end)
{
size_t sub_len = end - start + 1;
char * new_str = malloc(sub_len + 1); /* TODO: check malloc's return value */
strncpy(new_str, src, sub_len);
new_str[sub_len] = '\0'; /* new_str is of size sub_len + 1 */
return new_str;
}
int main(void)
{
char str[] = "111111000000000000000000111111";
char *sub_str = substr(str, 0, 5);
puts(sub_str);
free(sub_str);
return EXIT_SUCCESS;
}输出:
111111发布于 2011-12-26 06:34:32
示例:
char *substr(char *source, int startpos, int endpos)
{
int len = endpos - startpos + 2; // must account for final 0
int i = 0;
char *src, *dst;
char *ret = calloc(len, sizeof(char));
if (!ret)
return ret;
src = source + startpos;
dst = ret;
while (i++ < len)
*dst++ = *src++;
*dst = 0;
return ret;
}当然,当您不再需要返回代码时,请将其释放。你会注意到这个函数不会检查endpos和startpos的有效性。
https://stackoverflow.com/questions/8631897
复制相似问题