op_prg_str_decomp()
摘要
将由以字符分隔的字段组成的源字符串分解为一个字符串列表,列表中的每个字符串都是从源字符串中提取出的单个字段。
注意: 该内核过程是一个仅为向后兼容而保留的宏调用。新代码中请使用 prg_str_decomp()。
语法
op_prg_str_decomp (src_string, separators)
| 参数 | 类型 | 说明 |
|---|---|---|
src_string |
const char* |
待分解为字段的源字符串 [该字符串应包含一系列字段,字段之间可用 separators 参数中列出的任一分隔字符分隔。传入的字符串不会受该内核过程的影响。] |
separators |
const char* |
用于分隔源字符串字段的分隔字符 [该字符串应包含一组用于分隔源字符串各字段的字符。典型选择包括竖线(“|”)、逗号(“,”)、句点(“.”)或分号(“;”)字符。] |
返回类型
List*
指向从源字符串中提取出的字段列表的指针(即一个字符串列表)。
[该列表指针通常直接赋值给声明为 List* 的变量,如下方示例一节所示。即使列表中不包含任何字段值,也会返回有效的列表指针。若发生可恢复错误,则返回 OPC_NIL。]
示例
/* open and read in an address/stream translation table file */
table_list_ptr = op_prg_gdf_read ("addr_to_strm");
/* determine how many rows the table contains */
num_rows = op_prg_list_size (table_list_ptr);
/* loop through the table’s rows */
for (i = 0; i < num_rows; i++)
{
/* obtain a list of the columnar fields in each row */
field_list_ptr = op_prg_str_decomp (op_prg_list_access (table_list_ptr, i),
":");
/* extract the values of the two fields, and insert into the table matrix */
trans_tab [i].address = atoi (op_prg_list_access (field_list_ptr, 0));
trans_tab [i].stream = atoi (op_prg_list_access (field_list_ptr, 1));
/* deallocate the field list contents and list */
op_prg_list_free (field_list_ptr); op_prg_mem_free (field_list_ptr);
}
/* deallocate the table list contents and list */
op_prg_list_free (table_list_ptr); op_prg_mem_free (table_list_ptr);
详情
该内核过程动态分配返回的字段列表及其内容,且不会影响传入的参数。因此可以按照调用过程的需要对字段列表进行操作。列表完成使命后,其内容应通过内核过程 op_prg_list_free() 释放,列表本身应通过内核过程 op_prg_mem_free() 释放,以便其内存可以被回收用于其他用途。
源字符串中的字段可以包含空白字符(即空格或制表符)以及除分隔字符(用于分隔字段)以外的任何字符。不过,第一个字段开头的空白会被去除,这使得整组字段可以在源字符串中整体水平偏移,而不影响字段内容。在准备字段列表的过程中,完全由空白字符组成的字段不会被包含在内。例如,若源字符串包含十个字段(#0 – #9),且字段 #4 全部为空白,则返回的列表将包含九个字符串:字段 #0 至 #3,以及字段 #5 至 #9。
用途
提供一种从源字符串中提取多个字段的机制。这在处理表格信息时尤为有用:源字符串代表表格的一行,字符串的字段代表表格中的行列“单元格”。表格可以通过内核过程 op_prg_gdf_read() 从 GDF 读入为字符串列表,通过内核过程 op_prg_list_access() 按行序循环扫描,并且每个行字符串都可以用 op_prg_str_decomp() 分解为字段(左侧示例一节演示了这一技术)。
错误
- 可恢复错误:内存分配失败。
- 程序中止:段错误(由于字符串指针无效或字符串格式错误)。
参考
- 使用内核过程 op_prg_list_free() 释放列表的内容
- 使用内核过程 op_prg_mem_free() 释放列表结构
- 使用内核过程 op_prg_list_access() 获取列表中某个元素的指针
- 使用内核过程 op_prg_list_remove() 从列表中移除某个元素(并获得其指针)
- 使用内核过程 op_prg_gdf_read() 将 GDF 读入为字符串列表