简体   繁体   English

Android以''分隔

[英]Android split by ' '

I want split a string for example: 5121321 in 5 121 321, every 3 is a ' '. 我想分割一个字符串,例如:5 121 321中的5121321,每3个都是''。 I have that code: 我有那个代码:

private void compor()
{
    String dinheiro="5121321";

    char aux[]= new char[dinheiro.length()];

    for(int i=0;i<dinheiro.length();i++)
    {
       aux[i]=dinheiro.charAt(i);
    }

    int flag=0;

    String total="";
    for(int i=0;i<dinheiro.length();i++)
    {
        if(flag==3)
        {
            total+=' ';
            flag=0;
        }

        total += String.valueOf(aux[i]);
        flag++;
    }
    TextView txt = (TextView) findViewById(R.id.textView3);
    txt.setText(String.valueOf(total));
}

The problem is the output of this is: 512 132 1 and i want 5 121 321. Sorry my english. 问题是它的输出是:512 132 1,我想要5 121321。对不起,我的英语。 Somebody can help me?Thanks. 有人可以帮帮我吗?谢谢。

It looks like you're just trying to do general numeric formatting. 看来您只是在尝试进行一般的数字格式化。 A simple solution using framework utilities is: 使用框架实用程序的简单解决方案是

public static String splitNumericString(String numeric) throws NumberFormatException {
    // Create a new DecimalFormatSymbols instance and set the
    // grouping separator to a space character
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setGroupingSeparator(' ');

    // Construct a new NumberFormat defining a 3 digit grouping
    // pattern
    NumberFormat format = new DecimalFormat("#,###", symbols);

    // Converts the string into an actual numeric value
    long number = Long.parseLong(numeric);

    // Return the formatted string
    return format.format(number);
}

EDIT: Given @Squonk's info, this becomes a one-liner: 编辑:鉴于@ Squonk的信息,这成为一个单行:

return NumberFormat.getInstance(Locale.FRANCE).format(Long.parseLong(numeric));

Although you should catch the NumberParseException in case of an improperly formatted input string. 尽管在输入字符串格式不正确的情况下应该捕获NumberParseException。

(1) Just loop backwards through the string. (1)只需在字符串中向后循环。 And use pretty much the same idea you used. 并使用与您几乎相同的想法。 This will split it the way you want. 这将按照您想要的方式进行拆分。 (2) Alternatively, you can calculate where the first full triple starts by using the % (modulo) operator (I mean string length % 3). (2)或者,您可以使用%(模)运算符(我的意思是字符串长度%3)来计算第一个完整三元组的起始位置。

Sample code for approach (2): 方法(2)的示例代码:

public class Test007 {

    public static void main(String[] args) {

        String dinheiro="5121322";

        int i = dinheiro.length() % 3;

        String s1 = "";

        s1 = dinheiro.substring(0, i);

        String s2 = "";

        for (int k=i; k<dinheiro.length(); k+=3){
            if (k!=i || i>0){
                s2 += " ";
            }
            s2 += dinheiro.substring(k, k+3);
        }

        System.out.println(s1 + s2);

    }

}

Instead of catenating in a loop, use a stringbuilder: 不要在循环中连接,而是使用stringbuilder:

String input = /*...*/;
StringBuilder sb = new StringBuilder();
int i = 2;
for (char c : input.toCharArray()) {
    sb.append(c);
    i++;
    if (i == 3) {
        sb.append(' ');
        i = 0;
    }
}
String result = sb.toString();

Here's a variant to Peter Petrov's solution: 这是Peter Petrov解决方案的一个变体:

public static String group(String in) {
    // Get the length of the first group
    int i = (in.length() - 1) % 3 + 1;

    // Add the first group
    String out = in.substring(0, i);

    // Add the other groups, each prefixed with a space
    for (int k = i; k < in.length(); k += 3){
        out += " " + in.substring(k, k + 3);
    }

    return out;
}

We get the length of the first group, we initialize the output with that first group and then we go over the remainder of the input to append one group of 3 digits at a time. 我们得到第一组的长度,我们用第一组初始化输出,然后我们检查输入的其余部分,一次追加一组3位数。 That's really all there is to it. 这就是它的全部内容。

The tricky bit is in the first line. 棘手的一点是在第一行。 Just using in.length() % 3 doesn't work correctly, since that prevents the first group from ever having 3 digits. 仅使用in.length() % 3不能正常工作,因为这会阻止第一组包含3位数字。 For example, an input of "123456" would lead to i == 0 and an output of " 123 456" (note the unwanted space at the start). 例如,输入"123456"将导致i == 0并输出" 123 456" (注意开始时不需要的空间)。 Peter uses an if check to deal with this case, but it turns out you can also handle it by changing i a bit. Peter使用if检查来处理这种情况,但事实证明,您也可以通过稍微更改i来处理它。

We want the relation between in.length() and i to be like this: 我们希望in.length()i之间的关系像这样:

in.length() |   i | (in.length() - 1) % 3
------------------------------------------
         0  |   0 |                    -1
         1  |   1 |                     0
         2  |   2 |                     1
         3  |   3 |                     2
         4  |   1 |                     0
         5  |   2 |                     1
       ...  | ... |                   ...

Subtracting one before the modulo and adding it back afterwards gives us this relation (the partial result after the modulo is in the third column). 在模数之前减去一个并在之后添加它给我们这种关系(模数在第三列之后的部分结果)。 It even handles the special case where in is the empty string! 它甚至可以处理特殊情况,其中in是空字符串! :-P :-P

The solution is easier to write with simple arithmetic than with string manipulation: 使用简单的算法比使用字符串操作更容易编写解决方案:

public static String groupDigits(int amount) {  
    String total = "";

    while (amount > 0) {
        Integer digits = amount % 1000;
        amount = amount / 1000;
        total = digits.toString() + " " + total;
    }

    return total;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM