简体   繁体   中英

How can I print out an array list in a foursome fragmented list?

This is My Array code with given string numbers(0098765424100304643528):

public class Main
{

    public static void main(String[] args)
    {

        String mynumbers = "0098765424100304643528";
        int len = mynumbers.length();
        char[] tempCharArray = new char[len];
      for (int i = 0; i < len; i++)
         {
         tempCharArray[i] = mynumbers.charAt(i);
         System.out.print(tempCharArray[i]+"->");
      }

     System.out.println();

    }

}

this is the result after running :

0->0->9->8->7->6->5->4->2->4->1->0->0->3->0->4->6->4->3->5->2->8->

I want to change it such below (How can I fragment my array in foursome ?)

0098->7654->2410->0304->4352->8
System.out.println(StringUtils.join("0098765424100304643528".split("(?<=\\G.{4})"), "->"));

maybe you write the result is wrong as you say (foursome), if you just want the output foursome , you can do like that :

 for (int i = 0; i < len; i++)
 {
     tempCharArray[i] = mynumbers.charAt(i);
     System.out.print(tempCharArray[i]);
     if((i+1)%4==0)
     {
         System.out.print("->");
     }

 }

You could check if i is dividable by 4, if it is add an arrow, otherwise just print the number. Ie:

public class Main
{

public static void main(String[] args)
{

    String mynumbers = "0098765424100304643528";
    int len = mynumbers.length();
    char[] tempCharArray = new char[len];
  for (int i = 0; i < len; i++)
     {
     tempCharArray[i] = mynumbers.charAt(i);
     if((i % 4 == 0) && i > 0)
         System.out.print(tempCharArray[i]+"->");
     else
         System.out.print(tempCharArray[i]);
  }

 System.out.println();

}

}

Here the % is the modulus operator, which tells us the remainder of something divided by something else, ie: 5 % 4 = 1 since 5 / 4 = 1 * 4 + 1

We will check if value of i is not 0 and i is divisible by 4. If true, then print -> else print number without it.

public class Main
{
    public static void main(String[] args)
    {
        String mynumbers = "0098765424100304643528";
        int len = mynumbers.length();
        char[] tempCharArray = new char[len];
        for (int i = 0; i < len; i++)
        {
            tempCharArray[i] = mynumbers.charAt(i);
            if(i > 0 && i%4 == 0)
                System.out.print(tempCharArray[i]+"->");
            else
                System.out.print(tempCharArray[i]);
        }

        System.out.println();
    }
}

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