第七节 字符串处理(Character string handling)
第七节 字符串处理(Character string handling)
由 admin 于 周四, 2007-07-26 14:24 提交。I assume you are familiar with C language's string APIs, such as strlen(3) and strcpy(3). libapr provides some string APIs. They are almost same as the common(ANSI C) APIs. Why does libapr provide a yet another string APIs? The benefit of libapr's string APIs is related to memory pool. In a common C string handling, we have to write much memory management code. The following code is an example.
我假设你对C语言中的字符串处理API很熟悉,如strlen和strcpy。APR提供了一些字符串处理的API,他们和ANSI C的API非常相似。为什么APR还挺提供了另一套字符串的API呢?好处在于APR的字符串API同内存池相关联。在一个标准的C字符串处理中,我需要写很多内存管理的代码,代码如下:
/* ANSI C string example (a bit naive code) */
/* we concatenate three strings, s1, s2, s3 */
int len1 = strlen(s1);
int len2 = strlen(s2);
int len3 = strlen(s3);
int total_len = len1 + len2 + len3;
char *cat_str = malloc(total_len + 1);
strcpy(cat_str, s1);
strcat(cat_str, s2);
strcat(cat_str, s3);
/* later, we have to free the allocated memory */
free(cat_str);
The same thing is written with libapr as follows:
使用APR完成相同的工作代码如下:
/* pseudo code about libapr string APIs */
apr_pool_t *mp;
apr_pool_create(&mp, NULL);
/* apr_pstrcat() takes care of both memory allocation and string concatenation.
* If the concatenated string is read-only, we should use 'const char*' type. */
const char *cat_str = apr_pstrcat(mp, s1, s2, s3, NULL);
/* later, all we have to do is to destroy the memory pool to free all the memory */
apr_pool_destroy(mp);
Like apr_pstrcat(), apr_psprintf() allows you to write much simpler code. You can find other string APIs in apr_strings.h.
像apr_pstrcat(), apr_psprintf()这样的函数允许你写出更简单的代码,你可以在apr_strings.h.找到更多的字符串处理API。
最新评论
5 天 3 小时 前
1 周 16 分钟 前
1 周 18 分钟 前
1 周 1 天 前
1 周 1 天 前
4 周 4 天 前
1 年 11 周 前
1 年 11 周 前
1 年 49 周 前
1 年 51 周 前