Remove (empty) characters from a string as inspired by Ruby.

string_chomp(s)
string_chop(s)
string_trim(s, which, whitespace)
string_cut(s, which)

Arguments

s

A string (character) vector.

which

Denotes how to trim/cut a vector (both, left only, or right only).

whitespace

Denotes which whitespace characters to remove.

Value

Character vector.

Details

As inspired by Ruby, string_chomp() removes all whitespace characters in a string.

The function string_chop() removes the last character from a string.

The function string_trim() acts the same as trimws but its source code is more readable (in my opinion!).

string_cut() removes characters from either the left, right, or both ends of a string.

The synonym pattern of these functions are s_*() and *() (replace asterisks with upper, chomp, chop, and trim. s_cut() is the only synonym for string_cut()).

See also

Examples

string_chomp(rownames(mtcars))
#> [1] "MazdaRX4" "MazdaRX4Wag" "Datsun710" #> [4] "Hornet4Drive" "HornetSportabout" "Valiant" #> [7] "Duster360" "Merc240D" "Merc230" #> [10] "Merc280" "Merc280C" "Merc450SE" #> [13] "Merc450SL" "Merc450SLC" "CadillacFleetwood" #> [16] "LincolnContinental" "ChryslerImperial" "Fiat128" #> [19] "HondaCivic" "ToyotaCorolla" "ToyotaCorona" #> [22] "DodgeChallenger" "AMCJavelin" "CamaroZ28" #> [25] "PontiacFirebird" "FiatX1-9" "Porsche914-2" #> [28] "LotusEuropa" "FordPanteraL" "FerrariDino" #> [31] "MaseratiBora" "Volvo142E"
string_chop(rownames(mtcars))
#> [1] "Mazda RX" "Mazda RX4 Wa" "Datsun 71" #> [4] "Hornet 4 Driv" "Hornet Sportabou" "Valian" #> [7] "Duster 36" "Merc 240" "Merc 23" #> [10] "Merc 28" "Merc 280" "Merc 450S" #> [13] "Merc 450S" "Merc 450SL" "Cadillac Fleetwoo" #> [16] "Lincoln Continenta" "Chrysler Imperia" "Fiat 12" #> [19] "Honda Civi" "Toyota Coroll" "Toyota Coron" #> [22] "Dodge Challenge" "AMC Javeli" "Camaro Z2" #> [25] "Pontiac Firebir" "Fiat X1-" "Porsche 914-" #> [28] "Lotus Europ" "Ford Pantera " "Ferrari Din" #> [31] "Maserati Bor" "Volvo 142"
string_trim(" s ")
#> [1] "s"
string_cut("cut this please", which = 'both')
#> [1] "ut this pleas"