通過將字符串文本括在引號中,可以在Erlang中構(gòu)造一個(gè)字符串文字。需要使用雙引號(例如“ Hello World”)構(gòu)造Erlang中的字符串。
以下是在Erlang中使用字符串的示例-
-module(helloworld).
-export([start/0]).
start() ->
Str1 = "This is a string",
io:fwrite("~p~n",[Str1]).上面的示例創(chuàng)建了一個(gè)名為 Str1 的字符串變量。字符串“This is a string”已分配給變量并相應(yīng)顯示。
上面程序的輸出將是:
“This is a string”
接下來,我們將討論各種operations available for Strings。請注意,對于字符串操作,還需要包括字符串庫。
| 序號 | 字符串方法和描述 |
|---|---|
| 1 | 該方法返回特定字符串的長度。 |
| 2 | 該方法返回一個(gè)布爾值,以確定一個(gè)字符串是否等于另一個(gè)字符串。 |
| 3 | 該方法合并2個(gè)字符串并返回串聯(lián)的字符串。 |
| 4 | 該方法返回字符串中字符的索引位置。 |
| 5 | 該方法返回字符串中子字符串的索引位置。 |
| 6 | 該方法根據(jù)起始位置和起始位置的字符數(shù)返回原始字符串的子字符串。 |
| 7 | 該方法根據(jù)起始位置和起始位置的字符數(shù)返回原始字符串的子字符串。 |
-module(helloworld).
-import(string,[left/3]).
-export([start/0]).
start() ->
Str1 = "hello",
Str2 = left(Str1,10,$.),
io:fwrite("~p~n",[Str2]).當(dāng)我們運(yùn)行上面的程序時(shí),我們將得到以下結(jié)果。
"hello....."
該方法根據(jù)字符數(shù)從字符串的右邊返回子字符串。
right(str1,number)
str1 ?這是需要從中提取子字符串的字符串。
Number ?這是子字符串中需要出現(xiàn)的字符數(shù)。
根據(jù)字符串的右側(cè)和數(shù)字返回原始字符串的子字符串。
-module(helloworld).
-import(string,[right/2]).
-export([start/0]).
start() ->
Str1 = "hello World",
Str2 = right(Str1,2),
io:fwrite("~p~n",[Str2]).當(dāng)我們運(yùn)行上面的程序時(shí),我們將得到以下結(jié)果。
“l(fā)d”
該方法根據(jù)字符數(shù)從字符串的右邊返回子字符串。但是,如果數(shù)字大于字符串的長度,則可以選擇包含尾隨字符。
right(str1,number,$character)
str1 ?這是需要從中提取子字符串的字符串。
Number ?這是子字符串中需要出現(xiàn)的字符數(shù)。
$Character ?包含為結(jié)尾字符的字符。
根據(jù)字符串的右側(cè)和數(shù)字,從原始字符串返回子字符串。
-module(helloworld).
-import(string,[right/3]).
-export([start/0]).
start() ->
Str1 = "hello",
Str2 = right(Str1,10,$.),
io:fwrite("~p~n",[Str2]).當(dāng)我們運(yùn)行上面的程序時(shí),我們將得到以下結(jié)果。
".....hello"
該方法以小寫形式返回字符串。
to_lower(str1)
str1 ?這是需要從其轉(zhuǎn)換為小寫字母的字符串。
返回小寫的字符串。
-module(helloworld).
-import(string,[to_lower/1]).
-export([start/0]).
start() ->
Str1 = "HELLO WORLD",
Str2 = to_lower(Str1),
io:fwrite("~p~n",[Str2]).當(dāng)我們運(yùn)行上面的程序時(shí),我們將得到以下結(jié)果。
"hello world"
該方法以大寫形式返回字符串。
to_upper(str1)
str1 ?這是需要從其轉(zhuǎn)換為大寫字母的字符串。
Return Value ?返回大寫字符串。
-module(helloworld).
-import(string,[to_upper/1]).
-export([start/0]).
start() ->
Str1 = "hello world",
Str2 = to_upper(Str1),
io:fwrite("~p~n",[Str2]).當(dāng)我們運(yùn)行上面的程序時(shí),我們將得到以下結(jié)果。
"HELLO WORLD"
返回String的子字符串,從子位置Start到字符串的末尾,或者到Stop位置(包括Stop位置)。
sub_string(str1,start,stop)
str1 ?這是需要從其返回子字符串的字符串。
start ?這是子字符串的開始位置
stop ?這是子字符串的停止位置
返回String的子字符串,從子位置Start到字符串的末尾,或者到Stop位置(包括Stop位置)。
-module(helloworld).
-import(string,[sub_string/3]).
-export([start/0]).
start() ->
Str1 = "hello world",
Str2 = sub_string(Str1,1,5),
io:fwrite("~p~n",[Str2]).當(dāng)我們運(yùn)行上面的程序時(shí),我們將得到以下結(jié)果。
"hello"