Can i call macros something like this
\StrMid{\mystring}{\X}{\X+2}\par
So, i would like to have running window of length 3. And for this end i would like to be able to use temporary unnamed local variable \X+2 as i can in C++.
Can i call macros something like this
\StrMid{\mystring}{\X}{\X+2}\par
So, i would like to have running window of length 3. And for this end i would like to be able to use temporary unnamed local variable \X+2 as i can in C++.
You can use \numexpr\X+2 in order to evaluate the number of the end-'index' here.
Of course \numexpr\foo+\foobar will be an even more flexible solution.
Since \StrMid is not expandable the usability of \StrMid depends on the real design.
\documentclass{article}
\usepackage{xstring}
\begin{document}
\def\foo{10}
\def\foobar{14}
\def\mystring{And now for something completely different}
\StrMid{\mystring}{\foo}{\numexpr\foo+\foobar}
\end{document}
This yields or something c here.
A fully expandable function, with the help of expl3:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewExpandableDocumentCommand{\stringwindow}{mmm}
{
\tl_map_function:fN { \tl_range:onn { #1 } { #2 } { #3 } } \use:n
}
\cs_generate_variant:Nn \tl_map_function:nN { f }
\cs_generate_variant:Nn \tl_range:nnn { o }
\ExplSyntaxOff
\begin{document}
\newcommand\mystring{Andnowforsomethingcompletelydifferent}
\newcommand{\foo}{4}
\stringwindow{\mystring}{\foo}{\foo+2}
\edef\now{\stringwindow{\mystring}{\foo}{\foo+2}}
\texttt{\meaning\now}
\end{document}
The second and third argument of \stringwindow can be any integer denotation, that is, also counter registers, such as \value{chapter}, besides macros that expand to numbers.
Note: spaces are not preserved. A slower routine would be needed for this.
Here's a LuaLaTeX-based solution. Note that the macro \StrMid is fully expandable. All three arguments of \StrMid may consist of (or contain) macros; the only requirement is that the args evaluate to either a string (the first arg) or integers (the second and third arg). And, the result of \StrMid may be assigned to a new macro.
% !TeX program = lualatex
\documentclass{article}
\usepackage{luacode} % for "\luastring" macro
\newcommand\StrMid[3]{\directlua{tex.sprint(string.sub(\luastring{#1},#2,#3))}}
\newcommand\mystring{Andnowforsomethingcompletelydifferent}
\begin{document}
\newcommand\foo{2+2} % something that evaluates to an integer in Lua
\StrMid{\mystring}{\foo}{\foo+2} % returns "now"
% assign result of \StrMid to a LaTeX macro:
\newcommand\bbar{\StrMid{\mystring}{\foo+19}{\foo+21}}
\bbar % returns "let"
\end{document}
\StrMidcommand fromxstringpackage. – marsupilam Apr 24 '17 at 13:02