Home > Mobile >  How to make "loop" patern with zeroes behind the numbers i get from String?
How to make "loop" patern with zeroes behind the numbers i get from String?

Time:10-28

i want to ask something, i already get the number from string and put it inside string using replaceAll like this:

String y = "9.86-A5.321";
String x = y.replaceAll("\\D ","");
textview.setText(x);

Now my question is i need to make the number i get inside my String x (9865321) into something like this:

9865321
9000000
800000
60000
5000
300
20
1

How do i make it in Android Studio with Java?

CodePudding user response:

This is not tested, but the concept can be something like this:

for(int i=0; i<digits.length; i  ){
     StringBuild zeros = new StringBuild(digits[i]);
     String digitsTemp = digits.substring(i);
     for(int j=1; j<digitsTemp.length; j  )
     {
          zeros.append("0");
     }
}

The concept is iterate over your digit string, create a new string that will be the digit you want 0's and create a copy of original digits, starting from the digit you want and onward.

CodePudding user response:

You have the length of the original number string, so you can iterate over every character of that string and add as many zeros to it as the difference between the string length and which position the character occupies in it:

public class MyClass {
    public static void main(String args[]) {
      String string = "9865321";
      String string2= "";
      System.out.println(string);
      for (int i = 0; i< string.length(); i  ) {
          string2 = Character.toString(string.charAt(i));
          for (int j = string.length()-1; j > i ; j--) {
              string2 = string2 "0";
          }
          System.out.println(string2);
      }
    }
}

This is the trivial way to do it. You should use a StringBuilder for string2 instead, and you can probably optimize the two loops somehow, but the above code produces the correct output:

9865321
9000000
800000
60000
5000
300
20
1
  • Related