To truncate a String here is what I'm using :
String test1 = "this is test truncation 1.pdf";
String p1 = test1.substring(0, 10) + "...";
System.out.println(p1);
The output is 'this is te...' How can I access the file name extension so that output becomes : 'this is te... pdf' I could use substring method to access the last three characters but other file extensions could be 4 chars in length such as .aspx
Is there a regular expression I can use so that "this is test truncation 1.pdf" becomes "this is te... pdf"
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.
As Chris Olden mentioned above, using string::substr is a way to truncate a string. However, if you need another way to do that you could simply use string::resize and then add the ellipsis if the string has been truncated. You may wonder what does string::resize ?
You can do it all with a quick regex replace like this:
test1.replaceAll("(.{0,10}).*(\\..+)","$1...$2")
Do it like this :
String[] parts = test1.split("\\.");
String ext = parts[parts.length-1];
String p1 = test1.substring(0, 10) + "..."+ext;
System.out.println(p1);
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