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);
| improve this answer | |
  • 1
    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? – Gerrit Luimstra Dec 19 '17 at 15:02
  • @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). – yyny Dec 19 '17 at 15:13
  • 1
    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. – Adrian Larson Dec 19 '17 at 16:15

As an indicator to the user that the string has been shortened, also adding '...' to the end can be helpful.

There is a String method that does that:

String newString = sizeString.abbreviate(120);

This example from the help illustrates how the length of the '...' is also considered:

String s = 'Hello Maximillian';
String s2 = s.abbreviate(8);
System.assertEquals('Hello...', s2);
System.assertEquals(8, s2.length());
| improve this answer | |
  • BEST ANSWER FOR ME! – Bahman.A Jun 17 at 20:30

If you don't want an ellipsis character, use a quick regular expression to match only the first 80 (or whatever number) characters, and replace the string with just those.

yourString.replaceFirst('^(.{80}).*', '$1')
| improve this answer | |

Another way to do this, especially addressing the specific question,

My goal is to make it to 120 characters, retaining the left side

Use the left(length) method from the String class

and here's a usage example:

String s1 = 'abcdaacd';
String s2 = 
System.assertEquals('abc', s2);

and for your example would be,

string sizeString = 'Imagine this is more than 120 Characters';
string resizedString = '';
if(sizeString.Length() > 120){
    resizedString = sizeString.left(120);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.