To get first character from String in Java, use String. charAt() method. Call charAt() method on the string and pass zero 0 as argument. charAt(0) returns the first character from this string.
To get the first and last characters of a string, use the charAt() method, e.g. str. charAt(0) returns the first character, whereas str. charAt(str. length - 1) returns the last character of the string.
string str = (yourStringVariable + " "). Substring(0,5). Trim();
You can do exactly what you want with String.substring()
.
String str = "please truncate me after 13 characters!";
if (str.length() > 16)
str = str.substring(0, 13) + "..."
String foo = someString.substring(0, Math.min(13, someString.length()));
Edit: Just for general reference, as of Guava 16.0 you can do:
String truncated = Ascii.truncate(string, 16, "...");
to truncate at a max length of 16 characters with an ellipsis.
Aside
Note, though, that truncating a string for display by character isn't a good system for anything where i18n might need to be considered. There are (at least) a few different issues with it:
e
followed by a combining character that puts an accent on that e
.)For these reasons (and others), my understanding is that best practice for truncation for display in a UI is to actually fade out the rendering of the text at the correct point on the screen rather than truncating the underlying string.
Whenever there is some operation that you would think is a very common thing to do, yet the Java API requires you to check bounds, catch exceptions, use Math.min()
, etc. (i.e. requires more work than you would expect), check Apache's commons-lang. It's almost always there in a more concise format. In this case, you would use StringUtils#substring
which does the error case handling for you. Here's what it's javadoc says:
Gets a substring from the specified String avoiding exceptions.
A negative start position can be used to start n characters from the end of the String.
A null String will return null. An empty ("") String will return "".
StringUtils.substring(null, *) = null
StringUtils.substring("", *) = ""
StringUtils.substring("abc", 0) = "abc"
StringUtils.substring("abc", 2) = "c"
StringUtils.substring("abc", 4) = ""
StringUtils.substring("abc", -2) = "bc"
StringUtils.substring("abc", -4) = "abc"
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