Luca Carbone
Luca Carbone

Reputation: 11

Moving character at the beginning of the string maintaining the position of other characters intact in R

string <- paste(append(rep(" ", 7), append("A", append(rep(" ", 3), append("B", append(rep(" ", 17), "C"))))), collapse = "")

string
[1] "       A   B                 C"

how can I move A at the beginning of the string, keeping the position of B and C the same?

Upvotes: 0

Views: 213

Answers (1)

GKi
GKi

Reputation: 39667

You can use sub to get all spaces ( *) before a word (\\w+) and change their position \\2\\1.

sub("( *)(\\w+)", "\\2\\1", string)
#[1] "A          B                 C"

Or only for A:

sub("( *)A", "A\\1", string)

Upvotes: 3

Related Questions