【问题标题】:How to trim right whitespaces from String in prolog?如何在序言中从字符串中修剪正确的空格?
【发布时间】:2019-08-19 08:23:00
【问题描述】:

例如,我想从字符串中修剪右边的空格。 “狗”变成“狗”,“”变成“”。 这是如何实现的?

我知道 SWI 序言有修剪空白谓词,但它会从左右修剪字符串。

不过,我也在使用 GNU prolog,因此希望编写自己的解决方案。

【问题讨论】:

  • 作为yesterday's question 的后续,让我重申一下,调查dcgs 并尝试以一种新的方式从整体上解决您的问题是一个好主意,而不是因为尝试而感到沮丧将您的 Python 或其他任何东西直接转换为 Prolog。

标签: prolog whitespace trim


【解决方案1】:

您可以将字符串转换为字符列表(请参阅convert string to list in prolog),编写谓词以随心所欲地对其进行操作,然后将结果列表转换回字符串。

【讨论】:

【解决方案2】:

以下是在 SWI-Prolog 中使用 DCG 完成此操作的方法。我知道你说你正在使用 GNU Prolog,但也许这至少对使用 SWI-Prolog 的其他人有所帮助:

:- use_module(library(dcg/basics)).

trimmed(S) --> blanks, string(S), blanks, eos, !.

trim(S, T) :-
  string_codes(S, C), phrase(trimmed(D), C), string_codes(T, D).

【讨论】:

    【解决方案3】:

    GNU Prolog 是受支持的Logtalk 后端编译器之一。有了它,您可以访问(便携式)库(和开发人员工具!),让您轻松解决问题。例如,如果您的字符串使用原子表示,则可以使用 atom::replace_sub_atom/4 谓词:

    | ?- {types(loader)}.
    ...
    yes
    
    | ?- atom::replace_sub_atom(' ', '', 'Dog ', Output).          
    
    Output = 'Dog'
    
    yes
    | ?- atom::replace_sub_atom(' ', '', ' becomes ', Output).
    
    Output = becomes
    

    如果您使用双引号术语,它们的含义取决于double_quotes 标志值,在这种情况下,您可以使用list::subtract/3 谓词。例如:

    | ?- current_prolog_flag(double_quotes, Value).
    
    Value = codes
    
    yes
    
    yes
    | ?- list::subtract("Dog ", " ", Output).
    
    Output = [68,111,103]
    
    yes
    | ?- list::subtract(" becomes ", " ", Output).
    
    Output = [98,101,99,111,109,101,115]
    
    yes
    
    | ?- set_prolog_flag(double_quotes, chars).
    
    yes
    | ?- list::subtract("Dog ", " ", Output).
    
    Output = ['D',o,g]
    
    yes
    | ?- list::subtract(" becomes ", " ", Output).
    
    Output = [b,e,c,o,m,e,s]
    
    yes
    
    | ?- set_prolog_flag(double_quotes, atom).    
    
    yes
    | ?- atom::replace_sub_atom(" ", "", "Dog ", Output).
    
    Output = 'Dog'
    
    yes
    | ?- atom::replace_sub_atom(" ", "", " becomes ", Output).
    
    Output = becomes
    
    yes
    

    【讨论】:

      猜你喜欢
      • 2010-11-29
      • 2010-09-16
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 1970-01-01
      相关资源
      最近更新 更多