24

Given a certain string, e.g., s = "tesX123", how can I replace a certain character at a certain location?

In this example, the character at position 4 should be changed to "t".

Does a method exist in the style of setChar(s, 4, "t") which would result in test123?

2 Answers 2

34

Try substr()

substr(s, 4, 4) <- "t"
> s
#[1] "test123"
Sign up to request clarification or add additional context in comments.

Comments

10

We can use sub

sub("(.{3}).", "\\1t", s)
#[1] "test123"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.