Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Behavior of stri_sub() when from = 0 #494

Closed
UchidaMizuki opened this issue Jun 26, 2023 · 2 comments
Closed

Behavior of stri_sub() when from = 0 #494

UchidaMizuki opened this issue Jun 26, 2023 · 2 comments

Comments

@UchidaMizuki
Copy link

stri_sub(string, from, to = -1) is often used to get the end of a string.
As shown in the following reprex, if from = -2 or from = -1, the last two or one character can be obtained, respectively.

However, when from = 0, all strings are retrieved, not just "".
(I think this is because zeros are treated as positive numbers.)

This somewhat unpredictable behavior causes the following bug in stringr::str_trunc().
tidyverse/stringr#512

I think we need a function to get the end of the string or some option for stri_sub().

library(stringi)

stri_sub("xyz", -2, -1)
#> [1] "yz"
stri_sub("xyz", -1, -1)
#> [1] "z"
stri_sub("xyz", 0, -1)
#> [1] "xyz"

Created on 2023-06-26 with reprex v2.0.2

@gagolews
Copy link
Owner

This is a boundary case, this behaviour is intended.
It if for compatibility with stri_sub<- (the replacement version of the operator), which allows prepending a substring at the start of a given string.
In other words, think of 0 as 1.

@UchidaMizuki
Copy link
Author

Thanks. I see that special care is needed to get the tail of the string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants