如何移除字符串中的第n个字符?如何通过索引删除字符串中的字符(附R语言示例)
Hey there! Let's break down your two questions with practical R solutions, since your example uses an R vector.
1. Removing the nth character from a single string
If you need to strip out a specific position n from a string, you have a couple of reliable options:
Base R approach
Use substr() to split the string into two parts (before the nth character, and after it), then paste them together:
# Example: Remove the 3rd character from "Hello" my_string <- "Hello" n <- 3 result <- paste0(substr(my_string, 1, n-1), substr(my_string, n+1, nchar(my_string))) # Output: "Helo"
Here, substr(my_string, 1, n-1) grabs everything up to the (n-1)th character, and substr(my_string, n+1, nchar(my_string)) takes everything from the (n+1)th character to the end. Pasting them removes the nth character entirely.
Using the stringr package (tidyverse-friendly)
If you prefer regex or the tidyverse ecosystem, str_remove() with a custom regex works great:
library(stringr) my_string <- "Hello" n <- 3 result <- str_remove(my_string, sprintf("^(.{%d}).", n-1)) # Output: "Helo"
The regex ^(.{n-1}). matches the first (n-1) characters, then captures the nth character with the final .—replacing this match with nothing removes the nth character.
2. Deleting every second character from strings in an R vector
For your specific example (name <- c("Jackkk","Markkk","Jayyy")), where you want to remove every second character from each string (i.e., keep characters at positions 1, 3, 5, ...), here's how to do it efficiently:
Base R solution
Use sapply() to loop through each string, split it into individual characters, keep only the odd-indexed characters, then rejoin them:
name <- c("Jackkk","Markkk","Jayyy") # Remove every second character (keep positions 1,3,5...) clean_names <- sapply(name, function(x) { chars <- strsplit(x, "")[[1]] # Split string into single characters paste0(chars[seq(1, length(chars), 2)], collapse = "") # Keep odd positions & rejoin }) # Output: # Jackkk Markkk Jayyy # "Jckk" "Makk" "Jy"
Let's verify the results:
- "Jackkk" → J (1), c (3), k (5) → "Jckk"
- "Markkk" → M (1), r (3), k (5) → "Makk"
- "Jayyy" → J (1), y (3) → "Jy"
If you actually meant removing only the second character (not every second one) from each string, adjust the function to use the first question's logic:
clean_names_single <- sapply(name, function(x) paste0(substr(x,1,1), substr(x,3,nchar(x)))) # Output: # Jackkk Markkk Jayyy # "Jckkk" "Mrkkk" "Jyyy"
内容的提问来源于stack exchange,提问作者user19100232

