2016-02-18 39 views

回答

4

以同樣的方式,你會做手工:取每一個元素,檢查它是否已經在輸出,如果沒有,追加它:

@echo off 
setlocal enabledelayedexpansion 
set "string=test1 test2 test1 test3 test2 test3" 
set "newstring=" 
for %%i in (%string%) do (
    echo !newstring!|findstr /i "\<%%i\>" >nul || set "newstring=!newstring! %%i" 
) 
echo %newstring:~1% 

(注意:如果你想區分大小寫,請刪除/i

編輯爲處理完整的單詞而不是(可能的)子字符串。

+0

如果某個單詞作爲其他單詞的一部分被包含,則該方法失敗;例如:'set「string = test1 test2 tes test1 test3 test2 test3」'。 'tes'既沒有'test'字也沒有插在輸出中 – Aacini

+1

這很容易通過在'findstr/i'中添加字邊界來解決'\'我想。 – rojo

2

有幾種方法可以做到這一點;例如:

@echo off 
setlocal EnableDelayedExpansion 

set "in=test1 test2 tes test1 test3 test test2 test3" 


rem 1- Insert the word if it is not in the output already 
set "out= " 
for %%a in (%in%) do (
    if "!out: %%a =!" equ "!out!" set "out=!out!%%a " 
) 
echo "%out:~1,-1%" 


rem 2- Remove each word from output, then insert it again 
echo/ 
set "out= " 
for %%a in (%in%) do (
    set "out=!out: %%a = !" 
    set "out=!out!%%a " 
) 
echo "%out:~1,-1%" 
相關問題