Mike Warren
Mike Warren

Reputation: 3866

cmd equivalent of std::string::find_first:of

C++, Java, JavaScript, and possibly other programming languages all have a string function that searches a string for any character in a specified string pattern. For example, C++'s std::string::find_first_of works like this:

std::cout << "Vowel found in : " << "Search me for vowels".find_first_of("aeiou") << std::endl;
// should print "Vowel found in : 1". 

Is there any equivalent of that in CMD? I tried searching "dos string functions" but couldn't seem to find anything.

Upvotes: 3

Views: 68

Answers (2)

Richard
Richard

Reputation: 1131

There is no direct way, but you can write your own fairly easily.

To search for one character

@echo off
call :charposition "Search me for vowels" a pos
echo Found a at position %pos%

goto :eof
:charposition
set "string_search=%~1"
set /a char_pos=0
:charcheck
IF %string_search:~0,1%==%2 (
endlocal & set "%3=%char_pos%"
goto :eof
)
set "string_search=%string_search:~1%"
IF "%string_search%"=="" (
set "%3=Not Found"
goto :eof
)
set /a char_pos+=1
goto :charcheck

For multiple characters:

@echo off
call :charposition "Search me for vowels" aeiou pos
echo Found vowel at position %pos%

goto :eof
:charposition
set "string_search=%~1"
set /a char_pos=0
:charcheck
echo %2|find "%string_search:~0,1%">nul
IF %errorlevel%==0 (
endlocal & set "%3=%char_pos%"
goto :eof
)
set "string_search=%string_search:~1%"
IF "%string_search%"=="" (
set "%3=Not Found"
goto :eof
)
set /a char_pos+=1
goto :charcheck

See http://ss64.com/nt/syntax-substring.html for an explanation of the syntax for extracting substrings. As given, these are case sensitive.

Upvotes: 2

Magoo
Magoo

Reputation: 80123

Sadly, you don't explain why the output is "1" or what "1" signifies.

set "string=Search me for vowels"
echo %string%|findstr /i "a e i o u" >nul
echo %errorlevel%

should show errorlevel as 0 for "found" and 1 for "not found".

the string is echoed as input to findstr.

The /i makes the comparison case-insensitive.

the >nul suppresses output

the "a e i o u" means "search for one of these strings" (space-separated, 5 strings to locate)

Of course, this is a trivial example. findstr /? from the prompt or searching examples on SO would give you more tricks of the trade.

Upvotes: 1

Related Questions