简体   繁体   中英

Splitting up a String by given digits in Java

I have a String looking like this: 450ZVXX_OF_INV_CC 3 , which basically consists of three parts: Column 1 has 3 digits (in this case the numbers 450), Column 2 has 30 digits (in this case the digits and whitespaces until 3) and Column 3 has again 3 digits .

Now I need to split the String into the three parts using the digits 3, 30, 3 (stored in ints), because I have to build a table with above mentioned three columns.

So I basically want to take int1 = 3, get the first 3 digits of the String. Then I take int2 = 30, get the next 30 digits of the String. And then I take int3 = 3 to get the next 3 digits of the String.

FYI: The length digits 3, 30, 3 are the preset column length by the database system.

Regex is not useful, because I do not have any digits or characters, which I use to split the String. I will just use the preset numbers as explained above.

Programming Language: Java

Thanks in advance!

You can code it using String.substring method.

public class SubStrings {
  public static void main(String[] args) {
    String input = "450ZVXX_OF_INV_CC                 3";
    int first = 3;
    int second = 30;
    String part1 = input.substring(0, first);
    String part2 = input.substring(first, first+second);
    String part3 = input.substring(first+second);
    System.out.println(part1);
    System.out.println(part2);
    System.out.println(part3);
  }
}

This will work for you.

public class SubStrings {
  public static void main(String[] args) {
    String abc="123456789101112131415151617181999123";
    Integer first = Integer.parseInt(abc.substring(0, 3));
    BigInteger second = new BigInteger(abc.substring(3, 30));
    Integer third = Integer.parseInt(abc.substring(33, 36));
    System.out.println(first);
    System.out.println(second);
    System.out.println(third);
  }
}

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