Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract a substring from a string in java

Tags:

java

string

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.

like image 525
JavaMobile Avatar asked Dec 17 '22 18:12

JavaMobile


1 Answers

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.

like image 127
Chris Dennett Avatar answered Dec 30 '22 04:12

Chris Dennett