How to extract substring from string in java

Darling, I have a line like this: "... 1 name: john, 2name: lice, 3name: mike ...". I want to output its substring "1 name: john". its position in the row is not fixed. I also use the substring method but cannot get it. so that you could help me.

thanks.

+4
source share
2 answers
String s = str.split(",")[n].trim(); 

I suggest making a card 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); } 

Thus, the map will contain a list of identifiers for their value strings. If you want to store names only as elements of a map value:

 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 would be easier to use StringTokenizer in the second example for key = value pairs if you want to store more data, but I don't know what your separator is. You also need to store objects as map values ​​for storing information.

+6
source
 String s = "1name: john, 2name: lice, 3name: mike"; String[] names = s.split(", "); // comma and space for(String name : names){ System.out.println(name); } 
+6
source

Source: https://habr.com/ru/post/1335794/


All Articles