Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate character strings after first N characters

Tags:

r

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?

like image 505
akash87 Avatar asked Oct 15 '17 19:10

akash87


People also ask

How do I truncate a string?

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 cut a string to a certain length in python?

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.

How do I remove part of a string in R?

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.

How do you truncate a character in Java?

truncate() is a static method of the StringUtils class which is used to truncate a given string.


2 Answers

kind of faster ...

ifelse(nchar(a) > 13, paste0(strtrim(a, 10), '...'), a)
like image 74
TPArrow Avatar answered Nov 15 '22 20:11

TPArrow


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"
like image 36
Kalio Avatar answered Nov 15 '22 19:11

Kalio