PJLIB库基础框架-数据结构之字符串的使用

#include <stdio.h>
#include <pjlib.h>
#include <pj/types.h> // for pj_init.

#define THIS_FILE "main.c"

/*
字符串
struct pj_str_t
{
	char       *ptr;
	pj_ssize_t  slen;
};
*/

/*
字符串测试
*/
void string_test(void);

int main(int argc, char** argv)
{
	pj_status_t status;

	// pjlib库初始化
	status = pj_init();
	if (status != PJ_SUCCESS)
	{
		char errmsg[PJ_ERR_MSG_SIZE];
		pj_strerror(status, errmsg, sizeof(errmsg));
		PJ_LOG(1,(THIS_FILE, "%s: %s [status=%d]", pj_init, errmsg, status));
		return -1;
	}

	// 字符串测试
	string_test();

	// pjlib库关闭
	pj_shutdown();

	return 0;
}

/*
字符串测试
*/
void string_test(void)
{
	{
		// char ==> pj_str_t
		pj_str_t str;
		str = pj_str("Hello PJ_STR_T!");
		PJ_LOG(3, (THIS_FILE, "str = %.*s", str.slen, str.ptr));
	}

	{
		// pj_str_t ==> char
		pj_str_t str;
		char buffer[256];
		
		// 使用C字符串产生常量字符串
		pj_cstr(&str, "Hello C char!");

		memset(buffer, 0, sizeof(buffer));
		strncpy(buffer, str.ptr, str.slen);

		PJ_LOG(3, (THIS_FILE, "buffer = %s", buffer));
	}

	{
		// 无符号整数转换成字符串
		char buffer[256];
		unsigned val = 123456;
		
		memset(buffer, 0, sizeof(buffer));
		pj_utoa(val, buffer);

		PJ_LOG(3, (THIS_FILE, "val[%d] => buffer[%s]", val, buffer));
	}

	{
		// 将字符串转换为无符号整数
		unsigned val;
		pj_str_t str;

		str = pj_str("9367");
		val = pj_strtoul(&str);

		PJ_LOG(3, (THIS_FILE, "str[%.*s] => val[%d]", str.slen, str.ptr, val));
	}

	{
		// 删除字符串头尾空白符
		pj_str_t str;
		str = pj_str("  a b c 1 2 3 ");
		PJ_LOG(3, (THIS_FILE, "str[%.*s]", str.slen, str.ptr));
		pj_strtrim(&str);
		PJ_LOG(3, (THIS_FILE, "str[%.*s]", str.slen, str.ptr));
	}
}

你可能感兴趣的:(PJLIB库基础框架-数据结构之字符串的使用)