LaTeX: Access every character of an string variable
Simple Solution
This can be accomplished with the xstring
package. In particular, the \StrMid{string}{#2}{#3}
command allows you to take the substring of string from character positions #2 through #3.
\documentclass{article}
\usepackage{xstring}
\newcommand{\myText}[2]{\StrMid{2014/12/20}{#1}{#2}}
\begin{document}
\myText{1}{4}
\end{document}
Allowing for \myTest{}
However, the above solution always requires arguments for \myTest
.
It seems you want \myText{}
to give you the entire string 2014/12/20. So, we can make the first parameter optional (it defaults to the first position if not given in brackets), and the second parameter is the second position. We set up a conditional so that if the second position is empty, we just get the entire string.
\documentclass{article}
\usepackage{xstring}
\newcommand{\myText}[2][1]{
\ifx\\#2\\
{2014/12/20}
\else
\StrMid{2014/12/20}{#1}{#2}
\fi
}
\begin{document}
\myText{}
\myText[1]{4} \quad
\myText[6]{7} \quad
\myText[9]{10} \quad
\myText{7} \quad
\myText[6]{10}
\end{document}
With the stringstrings
package.
\documentclass{article}
\usepackage{stringstrings}
\begin{document}
\def\x{2014/12/20}
\substring{\x}{1}{4}\par
\substring{\x}{6}{7}\par
\substring{\x}{9}{$}\par% The $ implies the last character of the string.
\end{document}
Alternative with the listofitems
package, set up here to parse the input string on the basis of a /
separator.
\documentclass{article}
\usepackage{listofitems}
\begin{document}
\def\x{2014/12/20}
\setsepchar[.]{/}
\readlist\mydate{\x}
The year is \mydate[1]\par
The month is \mydate[2]\par
The day is \mydate[3]\par
\end{document}
A LuaLaTeX-based solution, which sets up a TeX macro called \substring
that takes three arguments.
The first argument of the macro \substring
is a string. It can be either a hard-coded string or a TeX macro that produces a string. E.g., if \myText
is defined via \newcommand{\myText}{2014/12/20}
, then \myText
could used as the first argument of \substring
.
The second and third arguments are the starting and ending indexes of the substring and are assumed to be integers. Please indicate if this assumption isn't valid.
% !TEX TS-program = lualatex
\documentclass{article}
\newcommand\substring[3]{%
\directlua{ tex.sprint ( string.sub ( "#1", #2, #3 ) ) } }
\begin{document}
\substring{2014/12/20}{1}{4}
\end{document}