简体   繁体   中英

how to extract a substring from a string in java

dear all, i have a string like this, "...1name: john, 2name: lice, 3name: mike...". i want to output its substring "1name: john". its position in the string is not fixed. i also use the substring method but can not get it. so could you give me a help.

thank you.

String s = str.split(",")[n].trim();

I suggest making a map if the position is random:

Map<Integer, String> m = new HashMap<Integer, String>();
for (String s : str.split(",")) {
   s = s.trim();
   int keyvalstart = -1;
   for (int i = 0; i < s.length(); i++) {
      if (!Character.isDigit(i)) {
         keyvalstart = i;
         break;
      }
   }
   if (keyvalstart == -1) continue;
   String s_id    = s.substring(0, keyvalstart - 1);
   String keyvals = s.substring(keyvalstart);
   int    id      = Integer.parseInt(s_id);
   m.put(id, keyvals);
}

The map will thus contain a list of person IDs to their respective value strings. If you wish to store names only as value elements of the map:

Map<Integer, String> m = new HashMap<Integer, String>();
for (String s : str.split(",")) {
   s = s.trim();
   int keyvalstart = -1;
   for (int i = 0; i < s.length(); i++) {
      if (!Character.isDigit(i)) {
         keyvalstart = i;
         break;
      }
   }
   if (keyvalstart == -1) continue;
   String s_id     = s.substring(0, keyvalstart - 1);
   int    id       = Integer.parseInt(s_id);
   String keyvals  = s.substring(keyvalstart);
   int    valstart = keyvals.indexOf("name: ") + "name: ".length();
   String name     = keyvals.substring(valstart);
   m.put(id, name);
}

It'd be easier to use a StringTokenizer in the second example for the key=value pairs if you want to store more data, but I don't know what your delimiter is. You'd also need to store objects as values of the map to store the info.

String s = "1name: john, 2name: lice, 3name: mike";
String[] names = s.split(", "); // comma and space

for(String name : names){
   System.out.println(name);
}

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