如何从字符串中删除所有单个字母?
说输入字符串是字符串
输出应该是什么字符串
我尝试了set string=%string: ? : %
命令,但?
通配符在这里不起作用。
我需要一个通用命令来删除字符串中的所有单个字母。
答案 0 :(得分:2)
鉴于输入字符串不包含其中一个字符!
,^
和"
,并且没有相邻的空格(将被压缩为一个),以下代码有效:
@echo off
setlocal EnableDelayedExpansion
set "string=what a string"
set "new=" & set "wrd=" & set "aug=%string% "
set "new=%aug: =" & (if defined wrd if not "!wrd:~1!"=="" set "new=!new! !wrd!") & set "wrd=%"
echo original: "%string%"
echo modified: "%new%"
endlocal
要维护相邻的空格,请按以下方式修改脚本:
@echo off
setlocal EnableDelayedExpansion
set "string=what a nice string"
set "new=" & set "wrd= " & set "aug=%string% "
set "new=%aug: =" & (if not "!wrd:~1!"=="" set "new=!new! !wrd!") & set "wrd=%"
echo original: "%string%"
echo modified: "%new%"
endlocal
答案 1 :(得分:1)
编辑 发现了一个字符串开头/结尾的漏洞,他们将不可避免地删除一个字符。
如果一行中有多个字符,则只删除第一个字符,以克服for循环中的重复%Letters%
。
@Echo off
Setlocal EnableExtensions EnableDelayedExpansion
Set "Letters= a b c d e f g h i j k l m n o p q r s t u v w x y z "
Set "String=i what a mess o things x"
IF "%~1" neq "" Set "String=%~1"
Echo Original String: %String%
For %%A in (%Letters%%Letters%) Do Set "String=!String: %%A = !"
:: Echo:%String:~0,2%|Findstr /Li "%Letters%" >Nul 2>&1 && Set "String=%String:~2%"
:: Echo:%String:~-2%|Findstr /Li "%Letters%" >Nul 2>&1 && Set "String=%String:~0,-2%"
Echo Processed String: %String%
示例输出:
> RemoveSingleLetters.cmd
Original String: i what a mess o things x
Processed String: what mess things
答案 2 :(得分:0)
试试这个功能:
@echo off
setlocal enabledelayedexpansion
SET TEST=Example1 : "< = > & ^^^! |"
SET TEST2=Example2 : ">>=^^^!>=^^^!<====<^^^!<=^^^!<=<=<&&<=^^^!<=<=|<&^=^=^!<||&==="
Set TEST3=Example3 : "?????? Hello ??????"
echo;%TEST% before Replace
call :ReplaceSpecialChar TEST "_"
echo;%TEST% after Replace
echo;
echo;%TEST2% before Replace
call :ReplaceSpecialChar TEST2 "_"
echo;%TEST2% after Replace
echo;
echo;%TEST3% before Replace
call :ReplaceSpecialChar TEST3 " "
echo;%TEST3% after Replace
pause>nul&exit
:ReplaceSpecialChar
call :ReplaceSpecialCharTmp %1 "?" %2
call :ReplaceSpecialCharTmp %1 "&" %2
call :ReplaceSpecialCharTmp %1 "<" %2
call :ReplaceSpecialCharTmp %1 ">" %2
call :ReplaceSpecialCharTmp %1 "|" %2
call :ReplaceSpecialCharTmp %1 "=" %2
call :ReplaceSpecialCharTmp %1 "^^^!" %2
goto :eof
:ReplaceSpecialCharTmp
set work=!%1!
set /a i = 0
:ReplaceLoop
if "!work:~%i%,1!"=="" (set %1=!work!&goto :eof)
if not "!work:~%i%,1!"=="%~2" (set /a i += 1&goto ReplaceLoop)
set head=!work:~0,%i%!
set /a i += 1
set work=!head!%~3!work:~%i%!
goto :ReplaceLoop