java - 如何按空格格式化文本?

标签 java android string-formatting number-formatting decimalformat

在 Android 应用程序中,我有一个字段,用户应在其中输入一些 14 位数字,例如 12345678901234。 我希望这个数字看起来像 12 3456 7890 1234。 我试图通过代码来做到这一点:

if((s.length() == 2 || s.length() == 7 || s.length() == 12)){
s.insert(s.length(), " ");
}

但是当用户开始在文本中间输入时,我的代码就出错了。

我尝试使用 DecimalFormat 类:

DecimalFormat decimalFormat = new DecimalFormat("##,####.#### ####");
String formattedText = decimalFormat.format(Double.parseDouble(etContent.getText().toString()));

但我收到 IllegalArgumentException。 任何想法如何做到这一点? P.S 主要问题是我应该“立即”格式化文本,例如:
1
12
12 3
12 34
12 345
12 3456
12 3456 7
12 3456 78
12 3456 789
12 3456 7890
12 3456 7890 1
12 3456 7890 12
12 3456 7890 123
12 3456 7890 1234

最佳答案

@Karthika PB 我认为它将删除第 3 个字符,即 12 4567,就像它会出现一样。 试试这个

    String seq = editText.getText().toString().trim();

    String newstring = "";
    for (int i = 0; i < seq.length(); i++) {

        if (i == 2 || i == 6 || i == 10) {
            newstring = newstring + " " + seq.charAt(i);

        } else
            newstring = newstring + seq.charAt(i);
    }

关于java - 如何按空格格式化文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29510842/

相关文章:

c# - 通过 LINQ 使用通用列表中的值格式化字符串

coffeescript - CoffeeScript 中的字符串插值

java - RabbitMQ – 在等待响应时取消 consumer.nextDelivery

java - 从命令行运行包中的java

android - location.getLatitude() 抛出 NullPointerException android

java - Android 应用程序键盘输入/发送键

java - 从哪里获得 Swagger 的 Bootstrap servlet?

java - 为什么我的数据报包响应不完整?

java - 安卓:CursorLoader、LoaderManager、SQLite

Python:无法格式化 SQL 查询字符串