用点替换字符

时间:2013-07-27 10:31:19

标签: java string replace

我希望能够从字符串的第8个字符替换为任何字符串中的点。如何才能做到这一点?

现在我有这个:

if(tempName.length() > 10)
{
     name.setText(tempName.substring(0, 10));
} else {
     name.setText(tempName);
}

4 个答案:

答案 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)

有几种方式。

1。 substring()和连接

// If > 8...
String dotted = src.substring(0, 8) + "...";
// Else...

String dotted = src.length() > 8 ? src.substring(0, 8) + "..." : src;

2。正则表达式

// If > 8...
String dotted = src.replaceAll("^(.{8}).+$", "$1...");
// Else...

String dotted = src.length() > 8 ? src.replaceAll("^(.{8}).+$", "$1...") : src;