Replace letter of command (control sequence)
The question is inconsistent, \expandafter\@gobble\string#1
indicates that the argument is a command sequence and the code strips the starting backslash. Then the usage cases are:
\startwiths{\plot} -> \splot
\startwithsUpper{\plot} -> \sPlot
Macro \startwithsUpper
can be implemented in an expandable manner by using \@Alph
instead of \uppercase
for converting a simple ASCII letter to its uppercase version:
\makeatletter
\newcommand*{\startwithsUpper}[1]{%
\csname
s%
\expandafter\expandafter\expandafter\FirstUpper
\expandafter\@gobble\string#1%
\endcsname
}
\def\FirstUpper#1{%
\ifnum`#1>`Z % case distinction between lowercase and uppercase letter
\@Alph{\numexpr`#1-`a+1\relax}% Convert lowercase letter
\else
#1% Keep uppercase letter
\fi
}
\makeatother
% Test
\edef\x{%
\unexpanded\expandafter\expandafter\expandafter{%
\startwithsUpper{\plot}%
}%
}
\makeatletter
\typeout{\string\startwithsUpper{\string\plot} -> \detokenize\expandafter{\x}}
\makeatother
\stop
Result:
\startwithsUpper{\plot} -> \sPlot
It's possible in several ways. Here's a (non expandable) one:
\documentclass{article}
\makeatletter
\newcommand{\startwithsUpper}[1]{%
\startwithsUpper@aux#1\relax
}
\def\startwithsUpper@aux#1#2\relax{%
\uppercase{\csname\initial@s #1}#2\endcsname
}
\def\initial@s{s}
\makeatother
\newcommand{\sPlot}{Here it is}
\begin{document}
\startwithsUpper{plot}
\end{document}
Here's an expandable one, with expl3
:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewExpandableDocumentCommand{\startwithsUpper}{m}
{
% \use:c is essentially \csname...\endcsname
\use:c
{
s % add the initial s
\text_titlecase_first:n { #1 }
}
}
\ExplSyntaxOff
\newcommand{\sPlot}{Here it is}
\begin{document}
\startwithsUpper{plot}
\end{document}
The following (more complicated) version accepts either a string or a control sequence as argument.
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewExpandableDocumentCommand{\startwithsUpper}{m}
{
\montecarlo_start_with_s_upper:n { #1 }
}
\cs_new:Nn \montecarlo_start_with_s_upper:n
{
\tl_if_single:nTF { #1 }
{
\token_if_cs:NTF #1
{
\__montecarlo_start_with_s_upper:e { \cs_to_str:N #1 }
}
{
\__montecarlo_start_with_s_upper:n { #1 }
}
}
{
\__montecarlo_start_with_s_upper:n { #1 }
}
}
\cs_new:Nn \__montecarlo_start_with_s_upper:n
{
\use:c
{
s
\char_titlecase:N #1
}
}
\cs_generate_variant:Nn \__montecarlo_start_with_s_upper:n { e }
\ExplSyntaxOff
\newcommand{\sPlot}{Here it is}
\begin{document}
X\startwithsUpper{plot}X
X\startwithsUpper{\plot}X
\end{document}
Here's a LuaLaTeX-based solution.
\documentclass{article}
\usepackage{luacode}
\begin{luacode}
function startwithsUpper ( s )
tex.sprint ( "\\s" .. string.gsub( s , "^%l", string.upper) )
end
\end{luacode}
\newcommand\startwithsUpper[1]{\directlua{startwithsUpper(\luastring{#1})}}
\newcommand\sPlot{Hello World} % dummy definition of "\sPlot"
\begin{document}
\startwithsUpper{plot}
\end{document}