我希望能够从字符串的第8个字符替换为任何字符串中的点。如何才能做到这一点?
现在我有这个:
if(tempName.length() > 10)
{
name.setText(tempName.substring(0, 10));
} else {
name.setText(tempName);
}
答案 0 :(得分:4)
如果要将8th
字符后面的子字符串替换为省略号,如果字符串长度大于10
,则可以使用单个String#replaceAll
来完成。你甚至不需要事先检查长度。只需使用以下代码:
// 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..."
);
另一种选择当然是substring
,您已经在其他答案中使用过了。
答案 1 :(得分:4)
public static String ellipsize(String input, int maxLength) {
if (input == null || input.length() <= maxLength) {
return input;
}
return input.substring(0, maxLength-3) + "...";
}
此方法将给出最大长度为maxLength
的字符串输出。使用MaxLength-3
...
后的所有字符
例如。 最大长度= 10
abc - &gt; ABC
1234567890 - &gt; 1234567890
12345678901 - &gt; 1234567 ...
答案 2 :(得分:3)
尝试用三个点替换?试试这个:
String original = "abcdefghijklmn";
String newOne = (original.length() > 10)? original.substring(0, 7) + "...": original;
三元运算符(A?B:C)执行此操作:A是布尔值,如果为true,则求值为B,其他位置求值为C.它可以不时地保存if
语句。
答案 3 :(得分:0)
有几种方式。
substring()
和连接// If > 8...
String dotted = src.substring(0, 8) + "...";
// Else...
或
String dotted = src.length() > 8 ? src.substring(0, 8) + "..." : src;
// If > 8...
String dotted = src.replaceAll("^(.{8}).+$", "$1...");
// Else...
或
String dotted = src.length() > 8 ? src.replaceAll("^(.{8}).+$", "$1...") : src;