I want to be able to replace from 8th character of string and on with dots in any string. How can this be done?
right now I have this:
if(tempName.length() > 10)
{
name.setText(tempName.substring(0, 10));
} else {
name.setText(tempName);
}
I want to be able to replace from 8th character of string and on with dots in any string. How can this be done?
right now I have this:
if(tempName.length() > 10)
{
name.setText(tempName.substring(0, 10));
} else {
name.setText(tempName);
}
If you want to replace substring after 8th character with an ellipsis, if string length is greater than 10, you can do it with single String#replaceAll. You don't even need to check for length before hand. Just use the below code:
// No need to check for length before hand.
// It will only do a replace if length of str is greater than 10.
// Breaked into multiple lines for explanation
str = str.replaceAll( "^" // Match at the beginning
+ "(.{7})" // Capture 7 characters
+ ".{4,}" // Match 4 or more characters (length > 10)
+ "$", // Till the end.
"$1..."
);
Another option is of course a substring, which you already have in other answers.
public static String ellipsize(String input, int maxLength) {
if (input == null || input.length() <= maxLength) {
return input;
}
return input.substring(0, maxLength-3) + "...";
}
This method will give string out put with max length maxLength. replacing all char after MaxLength-3 with ...
eg. maxLength=10
abc --> abc
1234567890 --> 1234567890
12345678901 --> 1234567...
Trying to replace with just three dots? Try this:
String original = "abcdefghijklmn";
String newOne = (original.length() > 10)? original.substring(0, 7) + "...": original;
Ternary operator ( A ? B : C ) does this: A is a boolean, if true, then evaluates to B, elsewhere evaluates to C. It can save you if statements every now and then.
A couple ways.
substring() and Concatenation// If > 8...
String dotted = src.substring(0, 8) + "...";
// Else...
or
String dotted = src.length() > 8 ? src.substring(0, 8) + "..." : src;
// If > 8...
String dotted = src.replaceAll("^(.{8}).+$", "$1...");
// Else...
or
String dotted = src.length() > 8 ? src.replaceAll("^(.{8}).+$", "$1...") : src;