简体   繁体   中英

Android split by ' '

I want split a string for example: 5121321 in 5 121 321, every 3 is a ' '. 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. 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:

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

Although you should catch the NumberParseException in case of an improperly formatted input string.

(1) Just loop backwards through the string. 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).

Sample code for approach (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:

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:

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. 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. For example, an input of "123456" would lead to i == 0 and an output of " 123 456" (note the unwanted space at the start). Peter uses an if check to deal with this case, but it turns out you can also handle it by changing i a bit.

We want the relation between in.length() and i to be like this:

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! :-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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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