Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Split into 3 Fields

Tags:

java

I have a String that looks like "NAME:City~FORMAT:S~PRINT:true"

I want to split and assign the value of "City" to field1, "S" to field2, and true to field3 (Boolean).

I know I can grind through this code with brute force, but is there a way to parse the value of the 2nd split into the fields without doing some sort of check on a subscript to see if it is an odd value (e.g. subscript 0 is the NAME, but I want subscript 1, which is "City").

   for (String element : text.split("~")) {
        for (String rule : element.split(":")) {
            System.out.println(rule);
        }

    }
like image 720
EdgeCase Avatar asked May 28 '26 13:05

EdgeCase


2 Answers

You could also avoid looping by doing something similar to this:

String[] flds = text.split("NAME:|~FORMAT:|~PRINT:");
String field1 = flds[1];
String field2 = flds[2];
String field3 = flds[3];
like image 195
robertstrack Avatar answered Jun 01 '26 06:06

robertstrack


You could just do

for (String element : text.split("~")) {
   System.out.println(element.split(":")[1]);
}

split() returns an array, and you want the second element, which has index 1.

like image 37
Keppil Avatar answered Jun 01 '26 04:06

Keppil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!