How to replace a character of a string based on its position in the string

Hi, I would like to do the following:
I have a string variable called UserInput: “1234”
I want to replace the second character of this string with the letter “p”.
So then the new string should look like this: “1p34”.

The way I am currently doing is: UserInput.Replace(UserInput(1),“p”)
However, this keeps on looking for the character “1” within the string, instead of looking up the position 1. It is returning: “p234”.

How can I get around this?

grafik

1 Like

Hi @nomi Welcome in community
please try this one

InputString.Replace(InputString.substring(your position,length of derived),Derived value)

@nomi
InputString.Replace(InputString.substring(2,1),p)

image

image

1 Like

Hello @nomi, It’s maybe a reason of space at the start of the string
Kindly try this

UserInput.Replace((UserInput.trim)(1),“p”)

image

Hi Thank you! I tried this but the same problem persists… I think there is something else wrong with my automation. Would it be possible for you to take a look at my file?
I tried it with another string “7777” instead just to see if it was a character issue. But the same thing happened.
It keeps on returning “pppp” instead of just “7p77”.

How can I fix this? Can I send you the file so you can take a look at the source?

Hi @nomi

Try with the below expression

"7777".Insert(1,"p").Remove(2,1)

image

Regards
Gokul

Hi @nomi

You can also try with Regex expression

System.Text.RegularExpressions.Regex.Replace("7777","(?<=\S)\S(?=\S{2})","p").ToString

image

image

Regards
Gokul

1 Like

Ohhh this worked! Thank you so much!!!

Great @nomi

Kindly close this topic by mark as solved

Regards
Gokul

Hey @nomi

Tell us the Correct input and output?

Regards
Gokul

image

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.