Skip to content

Commit c6a07ec

Browse files
Add "use_length" argument to str_pad() (#190)
Fixes #188
1 parent 67678a2 commit c6a07ec

File tree

4 files changed

+27
-5
lines changed

4 files changed

+27
-5
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# stringr (development version)
22

3+
* `str_pad()` gains `use_length` argument to control whether to use the total code
4+
point width or the number of code points as "width" of a string (#190).
5+
36
* `str_split_fixed()` now pads with `NA` rather than `" "` (#195).
47

58
* Experimental support for display `str_view()` with ANSI escapes, which

R/pad.r

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
#' @param width Minimum width of padded strings.
77
#' @param side Side on which padding character is added (left, right or both).
88
#' @param pad Single padding character (default is a space).
9+
#' @param use_length If `TRUE`, use the number of characters instead of the
10+
#' total of character widths (see [stringi::stri_width]).
911
#' @return A character vector.
1012
#' @seealso [str_trim()] to remove whitespace;
1113
#' [str_trunc()] to decrease the maximum width of a string.
@@ -24,12 +26,12 @@
2426
#'
2527
#' # Longer strings are returned unchanged
2628
#' str_pad("hadley", 3)
27-
str_pad <- function(string, width, side = c("left", "right", "both"), pad = " ") {
29+
str_pad <- function(string, width, side = c("left", "right", "both"), pad = " ", use_length = FALSE) {
2830
side <- match.arg(side)
2931

3032
switch(side,
31-
left = stri_pad_left(string, width, pad = pad),
32-
right = stri_pad_right(string, width, pad = pad),
33-
both = stri_pad_both(string, width, pad = pad)
33+
left = stri_pad_left(string, width, pad = pad, use_length = use_length),
34+
right = stri_pad_right(string, width, pad = pad, use_length = use_length),
35+
both = stri_pad_both(string, width, pad = pad, use_length = use_length)
3436
)
3537
}

man/str_pad.Rd

Lines changed: 10 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/testthat/test-pad.r

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,11 @@ test_that("directions work for simple case", {
1616
expect_equal(pad("left"), " had")
1717
expect_equal(pad("both"), " had ")
1818
})
19+
20+
test_that("padding based of length works", {
21+
# \u4e2d is a 2-characters-wide Chinese character
22+
pad <- function(...) str_pad("\u4e2d", ..., side = "both")
23+
24+
expect_equal(pad(width = 6), " \u4e2d ")
25+
expect_equal(pad(width = 5, use_length = TRUE), " \u4e2d ")
26+
})

0 commit comments

Comments
 (0)