nginx 字符串定义

typedef struct {
    size_t      len;    //数据长度
    u_char     *data;    //数据
} ngx_str_t;

len:字符串大小

data:字符串

有了len成员标志可以不使用C风格的字符串以’\0’结尾

字符串初始化

#define ngx_string(str)     { sizeof(str) - 1, (u_char *) str }
#define ngx_null_string     { 0, NULL }
#define ngx_str_set(str, text)                     \
(str)->len = sizeof(text) - 1; (str)->data = (u_char *) text
#define ngx_str_null(str)   (str)->len = 0; (str)->data = NULL

//初始化为"ngxinx string"
ngx_str_t str = ngx_string("ngxinx string");
//初始化为空串
ngx_str_t str = ngx_null_string;
//使用test赋值
ngx_str_t str;
char test[] = "ngxinx string";
ngx_str_set(str, text);
//清空数据
ngx_str_t str = ngx_string("ngxinx string");
ngx_str_null(str);

前两个宏是ngx\_str\_t在初始化时使用,后两个宏一般是ngx\_str\_t初始化完成之后使用


字符串操作函数

//单个字符大小写转换
#define ngx_tolower(c)      (u_char) ((c >= 'A' && c <= 'Z') ? (c | 0x20) : c)
#define ngx_toupper(c)      (u_char) ((c >= 'a' && c <= 'z') ? (c & ~0x20) : c)
//src转小写到dst
void ngx_strlow(u_char *dst, u_char *src, size_t n);
//比较前n个字符
#define ngx_strncmp(s1, s2, n)  strncmp((const char *) s1, (const char *) s2, n)
//比较字符串
#define ngx_strcmp(s1, s2)  strcmp((const char *) s1, (const char *) s2)
//查找字符串
#define ngx_strstr(s1, s2)  strstr((const char *) s1, (const char *) s2)
//字符串长度
#define ngx_strlen(s)       strlen((const char *) s)
//查找'\0',返回'\0'的位置,没找到返回n
size_t ngx_strnlen(u_char *p, size_t n);
//查找一个字符串
#define ngx_strchr(s1, c)   strchr((const char *) s1, (int) c)

//不区分大小写的比较函数
ngx_int_t ngx_strcasecmp(u_char *s1, u_char *s2);
ngx_int_t ngx_strncasecmp(u_char *s1, u_char *s2, size_t n);

//内存池复制字符串
u_char *ngx_pstrdup(ngx_pool_t *pool, ngx_str_t *src);

//内存拷贝
#define ngx_memcpy(dst, src, n)   (void) memcpy(dst, src, n)
//内存拷贝 返回末尾的位置
#define ngx_cpymem(dst, src, n)   (((u_char *) memcpy(dst, src, n)) + (n))

//格式化输出
u_char * ngx_cdecl ngx_sprintf(u_char *buf, const char *fmt, ...);
u_char * ngx_cdecl ngx_snprintf(u_char *buf, size_t max, const char *fmt, ...);
u_char * ngx_cdecl ngx_slprintf(u_char *buf, u_char *last, const char *fmt,...);

nginx虽然封装了ngx\_str\_t的结构,但是操作函数却没有以ngx\_str\_t为操作主体,还是以c字符串操作。大多函数只是加了‘ngx\_’的前缀。

标签: 字符串, nginx, string, char, ngx, define, str

相关文章推荐

添加新评论,含*的栏目为必填