有没有办法在不使用字符串的情况下删除句子中的字符?



>我正在尝试在不使用string模块的情况下删除句子中的字符。例如,"我想删除字符",我想删除句子中出现的所有"e",并计算我删除了多少"e"。

我使用字符串完成了它,代码如下:

-module(remove_count_characters).
-export([remove/2, count/2]).
remove(Sentence, Words)
->
string:split(Sentence, Words, trailing)
.
count(Sentence, Words) 
->
erlang:length(string:split(Sentence, Words, all)) - 1
.

我想你可以尝试使用re:replace/3。例如:

1> re:replace("Replaze", "z", "c", [global, {return, list}]). 
"Replace"
2> 1> re:replace("Remove word", "Remove ", "", [global, {return, list}]).
"word"

您也可以尝试使用列表生成器,例如删除e您可以尝试执行以下操作:

1> [X || X <- "eeeaeeebeeeceee", X =/= $e].
"abc"

并计算删除了多少e并获得结果可以如下所示:

1> List = "eeeaeeebeeeceee".
"eeeaeeebeeeceee"
2> Result = [X || X <- "eeeaeeebeeeceee", X =/= $e].
"abc"
3> {Result, Count} = {Result, length(List -- Result)}.
{"abc",12}

我想删除句子中出现的所有"e",并计算如何 我删除了许多"e"。

请记住,在 erlang 中,双引号字符串实际上是一个列表,其中包含双引号字符串中字符的 ascii 代码(整数(:

1> "abc" == [97, 98, 99].
true

将递归与几个累加器变量一起使用:

remove(TargetStr, Str) ->
remove(TargetStr, Str, _NewStr=[], _Count=0).
remove(_TargetStr, _Str=[], NewStr, Count) -> %when there are no more characters left in Str
{lists:reverse(NewStr), Count};
remove([Char]=TargetStr, _Str=[Char|Chars], NewStr, Count) -> %when Char matches the first character in Str
remove(TargetStr, Chars, NewStr, Count+1);
remove(TargetStr, _Str=[Char|Chars], NewStr, Count) -> %when the other clauses don't match, i.e. when Char does NOT match the first character in Str
remove(TargetStr, Chars, [Char|NewStr], Count).

在外壳中:

57> a:remove("e", "I want to remove characters").
{"I want to rmov charactrs",3}

使用列表:折叠器/3:

remove([TargetChar]=_TargetStr, Str) ->
Remover = fun(Char, _AccIn={NewStr, Count}) when Char==TargetChar ->
_AccOut={NewStr, Count+1};
(Char, _AccIn={NewStr, Count}) when Char=/=TargetChar ->
_AccOut={[Char|NewStr], Count} 
end,
lists:foldr(Remover, _InitialAcc={_NewStr=[], _Count=0}, Str).

我建议您使用如下所示的列表操作:

% remove("abcde",[],0) = {"abcd",1}
remove([],Acc,Total) -> {lists:reverse(Acc),Total};
remove([$e|L],Acc,Total) -> remove(L,Acc,Total +1 );
remove([E|L],Acc,Total ) -> remove(L,[E|Acc],Total).

相关内容