Split a string every 5 characters

后端 未结 5 2136
情深已故
情深已故 2020-12-03 02:49

Suppose I have a long string:

\"XOVEWVJIEWNIGOIWENVOIWEWVWEW\"

How do I split this to get every 5 characters followed by a space?

5条回答
  •  猫巷女王i
    2020-12-03 03:17

    You can try something like the following:

    s <- "XOVEWVJIEWNIGOIWENVOIWEWVWEW" # Original string
    l <- seq(from=5, to=nchar(s), by=5) # Calculate the location where to chop
    
    # Add sentinels 0 (beginning of string) and nchar(s) (end of string)
    # and take substrings. (Thanks to @flodel for the condense expression)
    mapply(substr, list(s), c(0, l) + 1, c(l, nchar(s))) 
    

    Output:

    [1] "XOVEW" "VJIEW" "NIGOI" "WENVO" "IWEWV" "WEW"
    

    Now you can paste the resulting vector (with collapse=' ') to obtain a single string with spaces.

提交回复
热议问题