Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace character at certain location within string

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?

like image 417
Markus Weninger Avatar asked Apr 13 '16 11:04

Markus Weninger


People also ask

How do you replace a character in a specific position in a string?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.

How do you replace a character in a specific position in a string Python?

replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).

How do you replace a character in a specific position in Java?

Like StringBuilder, the StringBuffer class has a predefined method for this purpose – setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter.

How do you replace part of a string with a value?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.


2 Answers

Try substr()

substr(s, 4, 4) <- "t"
> s
#[1] "test123"
like image 72
mtoto Avatar answered Sep 30 '22 23:09

mtoto


We can use sub

sub("(.{3}).", "\\1t", s)
#[1] "test123"
like image 22
akrun Avatar answered Oct 01 '22 00:10

akrun