I have a string as
[Ian Wood P. M. Visscher]
[Ian Wood L. Mengersen]
[Ian Wood]
[P. M. Visscher Ian Wood].
I want to write this string into two dimensional array. (ie)String
a[0][0]=Ian Wood ,
a[0][1]=P. M. Visscher,
a[1][0]=Ian Wood,
a[1][1]=L. Mengersen and so on.
Every time when I would give input, the names in the string will change.How do I split it and store it in the above form in the array. Please suggest any idea . Thanks in advance.Following is the code I worked on,but does not split properly.
String[] parts = output.split(" ");
String[][] table = new String[parts.length / 2][2];
for (int i = 0, r = 0; r < table.length; r++) {
table[r][0] = parts[i++];
table[r][1] = parts[i++];
}
System.out.println(java.util.Arrays.deepToString(table));
I assume that you mean initials as "certain delimiters", and your input string is an array of strings:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.System.out;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.compile;
public final class Q14914678 {
private static final Pattern pattern = compile("^\\s*((?:[a-z]+\\s*?)*)\\s*([a-z]\\..*)?", CASE_INSENSITIVE);
private static final String[] names = {
"Ian Wood P. M. Visscher",
"Ian Wood L. Mengersen",
"Ian Wood",
"P. M. Visscher Ian Wood"
};
public static void main(String[] args) {
final List<String[]> collected = new ArrayList<String[]>();
for ( final String name : names ) {
final Matcher matcher = pattern.matcher(name);
if ( matcher.matches() ) {
collected.add(new String[] {matcher.group(1), matcher.group(2)});
}
}
for ( final String[] array : pairArray ) {
out.println(array[0] + " / " + array[1]);
}
}
}
The result is as follows:
Ian Wood / P. M. Visscher
Ian Wood / L. Mengersen
Ian Wood / null
/ P. M. Visscher Ian Wood
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.