How to truncate a string to a specific length if it is longer?

  • How can I make it that I can reduce the length of a String? Like for example the string.Length() = 300.

    My goal is to make it to 120 characters, retaining the left side (e.g. NameOfThePerson to NameofThePers).

    string sizeString = 'Imagine this is more than 120 Characters';
    if(sizeString.Length() > 120){
        //insert logic here to make it 120 characters
  • Use substring method of String class

    Returns a new String that begins with the character at the specified zero-based startIndex and extends to the character at endIndex - 1.

    String sizeString = 'Let\'s Imagine this is more than 120 Characters';
    Integer maxSize = 120;
    if(sizeString.length() > maxSize ){
        sizeString = sizeString.substring(0, maxSize);

    Wouldn't calling the substring function without the `if` be sufficient? Because it will just grab as much as it can if it remains lower than 120?

    @GerritLuimstra I think so, and it might even be faster, since otherwise it would check the same condition two times. (I know that in low level programming languages like C/C++, removing the condition is definitely faster (Because of branch prediction), but maybe in Java, the overhead of calling the `substring` function outweighs this redundant condition checking).

    No it will error if you try to take a substring which is longer than the string itself. You should try it if you are unsure.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used