How to search a string for a literal character

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Streamrunner
Posts: 1
Joined: 19 Nov 2016 21:23

How to search a string for a literal character

#1 Post by Streamrunner » 29 Nov 2016 18:02

Hello, all, I have done some batch scripting with cmd.exe in the past, but have some new challenges.

Is there a way to find whether a certain character appears in a string?

Say I'm prompting for a single-word string (no need for special characters) using

Code: Select all

SET /P someword=Enter a word: 


What next?

ShadowThief
Expert
Posts: 1166
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: How to search a string for a literal character

#2 Post by ShadowThief » 29 Nov 2016 18:24

Personally, I'd use that string as a delimiter in a for /F loop and see if the second token had a value. It's even case sensitive.

Code: Select all

set "string=My fellow Americans"
for /f "tokens=1,2 delims=F" %%A in ("%string%") do if not "%%B"=="" echo F is present.


Note that if you're checking to see if % is present, you need to have %% in both the string and delims section.

Compo
Posts: 600
Joined: 21 Mar 2014 08:50

Re: How to search a string for a literal character

#3 Post by Compo » 30 Nov 2016 05:15

@ShadowThief, your code above doesn't work if searching for s instead of F

…perhaps:

Code: Select all

IF /I NOT "%someword%"=="%someword:F=%" ECHO=F is present

Post Reply