Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Characters in String

Tags:

I am trying to replace all instances of a character in a string of text with another character but I'm not succeeding.

Suppose the text is

cat rat mat fat 

I want the script to replace all the t's to p's

cap rap map fap 

What I have is the following but it seems to do little for me.

SET /P MY_TEXT=ENTER TEXT:  SET T2P=P  SET NEW_TEXT=%TEXT=:T!T2P!%  MSG * %NEW_TEXT% 
like image 984
LabRat Avatar asked Nov 20 '12 09:11

LabRat


People also ask

Can we use Replace method in string?

Java String replace() MethodThe replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.

Can you replace a character in a string Python?

The Python replace() method is used to find and replace characters in a string. It requires a substring to be passed as an argument; the function finds and replaces it. The replace() method is commonly used in data cleaning.


2 Answers

Try this

setlocal  set string=cat rat mat fat set string=%string:t=p% 
like image 129
Justin Avatar answered Oct 21 '22 23:10

Justin


You've got the = sign in the wrong place. Try:

setlocal enabledelayedexpansion set /P MY_TEXT=ENTER TEXT: SET T2P=P set NEW_TEXT=%MY_TEXT:T=!T2P!% MSG * %NEW_TEXT% 

You can also do the expansion the other way round, i.e.

set NEW_TEXT=!MY_TEXT:T=%T2P%! 
like image 24
Grhm Avatar answered Oct 22 '22 01:10

Grhm