Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the certain character in certain position in the string?

Tags:

r

I have a question that is how to replace a character which is in a certain place. For example:

str <- c("abcdccc","hijklccc","abcuioccc")
#I want to replace character "c" which is in position 3 to "X" how can I do that?
#I know the function gsub and substr, but the only idea I have got so far is 
#use if() to make it. How can I do it quickly?
#ideal result
>str
"abXdccc" "hijklccc" "abXuioccc"
like image 778
Codezy Avatar asked Jun 21 '18 08:06

Codezy


People also ask

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

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 I find a character at a specific position in a string?

The charAt() method of the String class returns the character at a given position of a String.


2 Answers

It's a bit awkward, but you can replace a single character dependent on that single character's value like:

ifelse(substr(str,3,3)=="c", `substr<-`(str,3,3,"X"), str)
#[1] "abXdccc"   "hijklccc"  "abXuioccc"

If you are happy to overwrite the value, you could do it a bit cleaner:

substr(str[substr(str,3,3)=="c"],3,3) <- "X"
str
#[1] "abXdccc"   "hijklccc"  "abXuioccc"
like image 51
thelatemail Avatar answered Oct 23 '22 06:10

thelatemail


I wonder if you can use a regex lookahead here to get what you are after.

str <- c("abcdccc","hijklccc","abcuioccc")
gsub("(^.{2})(?=c)(.*$)", "\\1X\\2", str, perl = T)

Or using a positive lookbehind as suggested by thelatemail

sub("(?<=^.{2})c", "X", str, perl = TRUE)

What this is doing is looking to match the letter c which is after any two characters from the start of the string. The c is replaced with X.

(?<= is the start of positive lookbehind

^.{2} means any two characters from the start of the string

)c is the last part which says it has to be a c after the two characters


[1] "abXcdccc"   "hijklccc"   "abXcuioccc"

If you want to read up more about regex being used (link)


Additionally a generalised function:

switch_letter <- function(x, letter, position, replacement) {
  stopifnot(position > 1)

  pattern <- paste0("(?<=^.{", position - 1, "})", letter)

  sub(pattern, replacement, x, perl = TRUE)

}

switch_letter(str, "c", 3, "X")
like image 34
zacdav Avatar answered Oct 23 '22 05:10

zacdav