6

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
}
5

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);
}
  • 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). – YoYoYonnY 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
19

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());
2

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')

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.