检查字符串中的字符

问题描述 投票:0回答:2

我需要检查一个字符串(在本例中称为“单词”),看看它是否包含字母(或字符,如果您愿意)。 我真的不需要知道这封信的位置,只要它存在就可以了。目前我有这个:

if character in word then //both "word" and "character" are string variables.
begin
{some code}
end;

问题是,这只是我抄袭了一个Python函数:

if character in word: //In python I would use an array for "word" 
    //some code

这似乎在 pascal 中不起作用。

这似乎是一个愚蠢的问题,但我对 pascal 非常陌生,并且确实在堆栈交换方面寻求帮助。任何有关如何检查字符串中的字符的帮助将不胜感激。

if-statement pascal
2个回答
1
投票
  if pos(character,word)>0 then
     ... some code

pos 对于字符和字符串都重载(对于子字符串匹配)

请注意,搜索区分大小写。如果你想要的话,字符和单词都大写()。


0
投票
  • 扩展帕斯卡(ISO 标准 10206):
    index('XYZ', 'Y') > 0
    
  • Delphi 和 FreePascal(在
    {$mode objFPC}
    {$longStrings on}
    中):
    'XYZ'.contains('X')
    
    您可能也对
    strUtils
    单元
    感兴趣,特别是…包含…函数。 FPC 附带兼容的
    strUtils
    实现。
  • in
    运算符仅针对
    set
    值定义。 左侧有合格会员值。 右侧有一个
    set
    表达式。
    program characterInString(output);
        { This function returns `true`, iff `needle` appears in `sample`. }
        function contains(
                sample: array[minimumIndex..maximumIndex: integer] of char;
                needle: char
            ): Boolean;
            var
                characters: set of char;
                i: integer;
            begin
                { Initialize with empty set. }
                characters := [];
                { Transform data: Collect all `char` values present. }
                for i := minimumIndex to maximumIndex do
                begin
                    { Here, `+` denotes the union of two `set` values. }
                    characters := characters + [sample[i]]
                end;
                { Analyze step: Is `needle` a member of `characters`. }
                contains := needle in characters
            end;
        { === MAIN ====================================================== }
        begin
            writeLn(contains('XYZ', 'Y'))
        end.
    
    Needle
    拥有数据类型
    char
    。 这是
    characters
    的基本类型(即
    char
    中的
    set of char
    )。 当且仅当某个值是指定集合的成员时,
    in
    运算符才会生成
    true
© www.soinside.com 2019 - 2024. All rights reserved.