Replacing white space with one single backslash

后端 未结 2 1137
青春惊慌失措
青春惊慌失措 2020-12-07 03:49

I want to replace a white space with ONE backslash and a whitespace like this:

\"foo bar\" --> \"foo\\ bar\"

I found how to replace wit

2条回答
  •  遥遥无期
    2020-12-07 04:06

    Your problem is a confusion between the content of a string and its representation. When you print out a string in the ordinary way in R you will never see a single backslash (unless it's denoting a special character, e.g. print("y\n"). If you use cat() instead, you'll see only a single backslash.

    x <- "foo bar"
    y <- gsub(" ", "\\\\ ", x)
    print(y)
    ## [1] "foo\\ bar"
    cat(y,"\n")  ## string followed by a newline
    ## foo\ bar
    

    There are 8 characters in the string; 6 letters, one space, and the backslash.

    nchar(y)  ## 8
    

    For comparison, consider \n (newline character).

    z <- gsub(" ", "\n ", x)
    print(z)
    ## [1] "foo\n bar"
    cat(z,"\n")
    ## foo
    ##  bar 
    nchar(z)  ## 8
    

    If you're constructing file paths, it might be easier to use forward slashes instead - forward slashes work as file separators in R on all operating systems (even Windows). Or check out file.path(). (Without knowing exactly what you're trying to do, I can't say more.)

提交回复
热议问题