简体   繁体   中英

Split String with comma and get the last two values

I have field type string that can get two type of values on it:

  1. simple field eg p1
  2. complex fields p1/p2/p3/p4

Now I have 2 questions:

  1. how can I identify that the type is complex with little effort as possible since the check is runs in loop?
  2. when I got type complex I need to store the last two properties for example p3 and P4?

just use split operation and check length.

String[] prop = strprop.split("/");
if(prop.length > 1){
    String El = prop[prop.length];
    String El0 = prop[prop.length-1];
}

To answer 1) I would use (assuming variable str contains your value):

str.contains("/"); // If true => complex type

For 2):

String[] vals = str.split("/");
String lastVal = vals[vals.length-1];
String preLastVal = vals[vals.length-2];

Please note that you should check for array length before trying to get the values, otherwise you're likely to get an ArrayIndexOutOfBoundsException.

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