7.48 如何手動轉換字符串編碼
1.問題提出
如何將英文的字符串轉換成UTF-8格式的字符串?
2.問題解答
可以使用lr_convert_string_encoding函數將字符串從一種編碼手動轉換為另一種編碼(UTF-8、Unicode或本地計算機編碼)。
該函數的語法如下。
lr_convert_string_encoding(char * sourceString, char * fromEncoding, char * toEncoding, char * paramName)
該函數將結果字符串(包括其終止NULL)保存在第四個參數paramName中。如果成功,則返回0;失敗,則返回−1。
fromEncoding和toEncoding參數的格式如下。
LR_ENC_SYSTEM_LOCALE NULL
LR_ENC_UTF8 "utf-8"
LR_ENC_UNICODE "ucs-2"
在以下示例中,lr_convert_string_encoding將英文“Hello world”和字符串“我愛LR”由系統本地環境轉換為Unicode,腳本代碼如下。
Action()
{
int rc = 0;
rc= lr_convert_string_encoding("Hello world", LR_ENC_SYSTEM_LOCALE, LR_ENC_UNICODE,
"strUnicode");
if(rc < 0)
{
lr_output_message("轉換\"Hello world\"失敗!");
}
rc= lr_convert_string_encoding("我愛LR", LR_ENC_SYSTEM_LOCALE, LR_ENC_UNICODE,
"strUnicode");
if(rc < 0)
{
lr_output_message("轉換\"我愛LR\"失敗!");
}
return 0;
}
如果在“Run-time Settings”日志頁啟用了“Extended log”組的“Parameter substitution”復選框,則在執行日志中,輸出窗口將顯示以下信息。
Running Vuser...
Starting iteration 1.
Starting action Action.
Action.c(4): Notify: Saving Parameter "strUnicode = H\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00\x00\x00"
Action.c(9): Notify: Saving Parameter "strUnicode = \x11b1rL\x00R\x00\x00\x00"
Ending action Action.
Ending iteration 1.
Ending Vuser...
從上面的腳本和代碼中不難看出,應用lr_convert_string_encoding()函數可以將轉換后的字符保存到strUnicode變量中。“H\x00e\x00l\x00l\x00o\x00\x00w\x00o\x00r\x00l \x00d\x00\ x00\x00”這段Unicode文本對應的是“Hello world”英文文本,而“\x11b1rL\ x00R\x00\x00\x00”對應的是“我愛LR”字符串。