在字符串中查找字符

在字符串中查找字符

我正在寻找一种检查字符串中是否包含“外来字符”的解决方案。

我发现检查字符串是否包含给定字符,它仅查找一个字符。但是,我无法满足我的需求。

即:让主字符串为asdf

\check{asdf}{asdfgh}asdfgh应该返回 true,因为我的主字符串是包含非外来字符的字符串的真正子集。

\check{asdf}{hgfdsa}也应该返回 true。同样\check{adfs}{hdagsf}- 字符的顺序不重要,只关心出现次数。

\check{asdf}{asdghj}应该返回 false,因为f主字符串中的字符是外星人,因为它不在asdghj

欢迎任何想法。

答案1

\documentclass{article}

\usepackage{xinttools}

\makeatletter
\newcommand\mycheck[2]{%
   \xintFor*##1in{#1}:
   {%
      \in@{##1}{#2}%
      \unless\ifin@\expandafter\xintBreakFor\fi
   }%
   \ifin@\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi
}
\makeatother

\newcommand\test[2]{#1 in #2 ? \mycheck{#1}{#2}{TRUE}{FALSE}}
\begin{document}

\test{asdf}{asdfgh}

\test{asdf}{hgfdsa}

\test{asdf}{asdghj}
\end{document}

在此处输入图片描述

答案2

您可以测试第一个字符串中的每个项目是否在第二个字符串中;在任何“不匹配”时停止并返回 false。

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\checkTF}{mmmm}
 {
  \stringchecker_if_string_in:nnTF { #1 } { #2 } { #3 } { #4 }
 }

\bool_new:N \l__stringchecker_temp_bool

\prg_new_protected_conditional:Nnn \stringchecker_if_string_in:nn { T, F, TF }
 {
  % set the temporary boolean to true; it will remain such
  % unless a nonmatch will happen
  \bool_set_true:N \l__stringchecker_temp_bool
  % map over the substring to find
  \str_map_inline:nn { #1 }
   {
    % do nothing if there is a match; ##1 is the current item, #2 the string to search in
    \str_if_in:nnF { #2 } { ##1 }
     {
      % a nonmatch breaks the mapping and sets the boolean to false
      \str_map_break:n { \bool_set_false:N \l__stringchecker_temp_bool }
     }
   }
  \bool_if:NTF \l__stringchecker_temp_bool
   {% there was no nonmatch, return true
    \prg_return_true:
   }
   {% a nonmatch was found, return false
    \prg_return_false:
   }
 }
\ExplSyntaxOff

\begin{document}

\checkTF{asdf}{asdfgh}{TRUE}{FALSE}

\checkTF{asdf}{hgfdsa}{TRUE}{FALSE}

\checkTF{asdf}{asdghj}{TRUE}{FALSE}

\checkTF{}{asdghj}{TRUE}{FALSE}

\checkTF{a}{}{TRUE}{FALSE}

\end{document}

在此处输入图片描述

稍微更高效的版本,它从第一个参数中一次吸收一个标记。

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\checkTF}{mmmm}
 {
  \stringchecker_if_string_in:nnTF { #1 } { #2 } { #3 } { #4 }
 }

\prg_new_protected_conditional:Nnn \stringchecker_if_string_in:nn { T, F, TF }
 {
  \__stringchecker_check:nN { #2 } #1 \q_nil
 }

\cs_new_protected:Nn \__stringchecker_check:nN
 {
  \quark_if_nil:NTF #2
   {
    \prg_return_true:
   }
   {
    \str_if_in:nnTF { #1 } { #2 }
     {
      \__stringchecker_check:nN { #1 }
     }
     {
      \__stringchecker_stop:w
     }
   }
 }
\cs_new:Npn \__stringchecker_stop:w #1 \q_nil
 {
  \prg_return_false:
 }
\ExplSyntaxOff

\begin{document}

\checkTF{asdf}{asdfgh}{TRUE}{FALSE}

\checkTF{asdf}{hgfdsa}{TRUE}{FALSE}

\checkTF{asdf}{asdghj}{TRUE}{FALSE}

\checkTF{}{asdghj}{TRUE}{FALSE}

\checkTF{a}{}{TRUE}{FALSE}

\end{document}

相关内容