I have a vector of strings that range from 3 characters to 59 characters. I am trying to truncate any string greater than 13 characters with "..." after 10 characters. For example if
a <- c("AMS", "CCD", "TCGGCKGTPGPHOLKP", "NOK", "THIS IS A LONG STRING", "JSQU909LPPLU")
Then I want to get
"AMS" "CCD" "TCGGCKGTPG..." "NOK" "THIS IS A ..." "JSQU909LPPLU"
I am sure it is going to require an if
statement and a gsub
and my issue is the gsub
. Any thoughts?
Using String's split() Method. Another way to truncate a String is to use the split() method, which uses a regular expression to split the String into pieces. The first element of results will either be our truncated String, or the original String if length was longer than text.
How do you split a string by character length in Python? Use range() and slicing syntax to split a string at every nth character. Use a for-loop and range(start, stop, step) to iterate over a range from start to stop where stop is the len(string) and step is every number of characters where the string will be split.
Remove Specific Character from StringUse gsub() function to remove a character from a string or text in R. This is an R base function that takes 3 arguments, first, the character to look for, second, the value to replace with, in our case we use blank string, and the third input string were to replace.
truncate() is a static method of the StringUtils class which is used to truncate a given string.
kind of faster ...
ifelse(nchar(a) > 13, paste0(strtrim(a, 10), '...'), a)
I think the simplest way to do that is by using substr
, that does not require any packages
a <- c("AMS", "CCD", "TCGGCKGTPGPHOLKP", "NOK", "THIS IS A LONG STRING","JSQU909LPPLU")
#It will keep only chars from 1-10 for each element
substr(a,1,10)
[1] "AMS" "CCD" "TCGGCKGTPG" "NOK" "THIS IS A "
[6] "JSQU909LPP"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With