使用 xstring 包控制填充

使用 xstring 包控制填充

为了用预定义的填充来填充一些文本,我使用了 xstrings 包

我现在的代码是

\documentclass{minimal}
\usepackage{xstring}

\newcommand\padfrom[2]{\StrGobbleLeft{#1}{\StrLen{#2}}#2}


\begin{document}
\begin{tabular}{c|c}
\textbf{use} & \textbf{Expected} \\
\hline\
\padfrom{0000}{ab} & 00ab \
\end{tabular}
\end{document}

但是编译失败(我只能在将原始数字放在那里时编译 StrGobbleLeft 用法,使用宏/命令似乎不起作用

答案1

这是一个相当常见的问题:\StrLen不直接产生数字,而是产生获取数字的所有指令。使用方法如下:

\newcommand\padfrom[2]{\StrLen{#2}[\templen]\StrGobbleLeft{#1}{\templen}#2}

所以它\templen实际上只包含代表字符串长度的数字。

答案2

如果引用字符串(长度)是固定的,则无需在表中重复引用字符串。更重要的是,请注意条目的结果<space>abc<space>不是您所期望的。

\documentclass{article}
\usepackage{xstring}
\usepackage{array,hhline}
\newcommand\fletters[1]{\StrLen{#1}[\templen]\StrGobbleLeft{0000}{\templen}#1}
\def\jline{\\\hhline{*2{|=}|}}

\begin{document}
\begin{tabular}{*2{|>{\centering\arraybackslash}m{3cm}}|}\hline
\textbf{Given} & \textbf{Expected}\jline
\fletters{ abc} & 00ab \\\hline
\fletters{abcde} & \fletters{ab} \\\hline
\fletters{a} & \fletters{ab} \\\hline
\end{tabular}
\end{document}

编辑

这是一个更加强大的解决方案。

\documentclass{article}
\usepackage{catoptions}
\usepackage{array,hhline}
\makeatletter
% \getStringLength[<result.cmd>]{<string>}
% \getStringLength*[<result.cmd>]{<stringcmd>}
% The default of <result.cmd> is \slength.
\robust@def*\getStringLength{\cpt@teststopt\get@StringLength\slength}
\robust@def*\get@StringLength[#1]#2{%
  \begingroup
  \cpt@stchoose{cpt@st}{#2}\reserved@a\getStringLength
  \despacecontent\reserved@a
  \@tempcnta\z@pt
  \expandafter\cpttfor\reserved@a\dofor{\advance\@tempcnta\@ne}%
  \edef\slength{\the\@tempcnta}%
  \postgroupdef\slength\endgroup
}
% \stringGobbleLeft[<result.cmd>]{<string>}{<number>}
% \stringGobbleLeft*[<result.cmd>]{<stringcmd>}{<number>}
% The default of <result.cmd> is \rstring.
\robust@def*\stringGobbleLeft{\cpt@teststopt\string@GobbleLeft\rstring}
\robust@def*\string@GobbleLeft[#1]#2#3{%
  \begingroup
  \cpt@stchoose{cpt@st}{#2}\reserved@a\stringGobbleLeft
  \despacecontent\reserved@a
  \@tempcnta\z@pt
  \def#1{}%
  \expandafter\cpttfor\reserved@a\dofor{%
    \advance\@tempcnta\@ne
    \ifnum\@tempcnta>#3\relax
      \edef#1{\expandcsonce#1\unexpanded{##1}}%
    \fi
  }%
  \postgroupdef#1\endgroup
}

% Tests:
\stringGobbleLeft{ 0 0 0 0 }{4}
%\show\rstring % -> empty
% It is possible to take account of unprotected spaces in the string, 
% but I am not sure that is what you need.
\stringGobbleLeft{ 0{ }0{ }0 0 }{4}
%\show\rstring % -> 00

\robust@def*\fletters#1{%
  \getStringLength{#1}\stringGobbleLeft{0000}\slength
  \rstring\cpttrimspace{#1}%
}

\def\jline{\\\hhline{*2{|=}|}}
\makeatother

\begin{document}
\begin{tabular}{*2{|>{\centering\arraybackslash}m{3cm}}|}\hline
\textbf{Given} & \textbf{Expected}\jline
\fletters{ abc } & 00ab \\\hline
\fletters{abcde} & \fletters{ab} \\\hline
\fletters{ a } & \fletters{ab} \\\hline
\end{tabular}
\end{document}

相关内容