4

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.

1
  • thank you Chris Dennett and hilal, i have done with your help. Commented Jan 17, 2011 at 9:14

2 Answers 2

6
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.

Sign up to request clarification or add additional context in comments.

1 Comment

thx, but how could we decide the n? because the position is unknown
6
String s = "1name: john, 2name: lice, 3name: mike";
String[] names = s.split(", "); // comma and space

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.