> Erlang中文手册 > sub_word/3 获取指定位置的单词

string:sub_word/3

获取指定位置的单词

用法:

sub_word(String, Number, Character) -> Word

内部实现:

-spec sub_word(String, Number, Character) -> Word when
      String :: string(),
      Word :: string(),
      Number :: integer(),
      Character :: char().

sub_word(String, Index, Char) when is_integer(Index), is_integer(Char) ->
    case words(String, Char) of
	Num when Num 
	    [];
	_Num ->
	    s_word(strip(String, left, Char), Index, Char, 1, [])
    end.

s_word([], _, _, _,Res) -> reverse(Res);
s_word([Char|_],Index,Char,Index,Res) -> reverse(Res);
s_word([H|T],Index,Char,Index,Res) -> s_word(T,Index,Char,Index,[H|Res]);
s_word([Char|T],Stop,Char,Index,Res) when Index  
    s_word(strip(T,left,Char),Stop,Char,Index+1,Res);
s_word([_|T],Stop,Char,Index,Res) when Index  
    s_word(T,Stop,Char,Index,Res).

通过一个分隔符 Character 来把字符串 String 分成若干个单词,然后返回第 Number 个的单词

string:sub_word("abxcdxefxg", 2, $x).