how to split a string on certain conditions
java
Solution
1st Way:
- You can first split your string on the basis of `:::`. This will give you an array of length 3. You would be interested in the `2nd` and the `3rd` element of your array.
- Then split the `2nd element` of your array on `::`. This will give you an array containing `each name`.
Iterate over the `2nd array` and print each name with the `3rd element` of your first array.
String str = "books/eh/grayL88/WilliamsMC88:::M. Howard Williams::" +
"P. A. Massey::Jim A. Crammond:::Benchmarking Prolog for " +
"Database Applications.";
String[] arr = str.split(":::");
String[] innerArr = arr[1].split("::");
for (String name: innerArr) {
System.out.println(name + " -- " + arr[2]);
}
OUTPUT: -
M. Howard Williams -- Benchmarking Prolog for Database Applications. P. A. Massey -- Benchmarking Prolog for Database Applications. Jim A.Crammond -- Benchmarking Prolog for Database Applications.
2nd Way:
Or, you can split on `:::?`. This will split on `::` or `:::`, that will get each individual elements in your first array only (Will work only for `3` names. For more, you should better use the first one)
String[] arr = str.split(":::?");
System.out.println(arr[1] + " - " + arr[4]);
System.out.println(arr[2] + " - " + arr[4]);
System.out.println(arr[3] + " - " + arr[4]);
OUTPUT: -
M. Howard Williams - Benchmarking Prolog for Database Applications. P. A. Massey - Benchmarking Prolog for Database Applications. Jim A. Crammond - Benchmarking Prolog for Database Applications.
Problem
I have a following string books/eh/grayL88/WilliamsMC88:::M. Howard Williams::P. A. Massey::Jim A. Crammond:::Benchmarking Prolog for Database Applications. How should i use or in other words what to use so that at last i may get M. Howard Williams -- Benchmarking Prolog for Database Applications. P. A. Massey -- Benchmarking Prolog for Database Applications. Jim A. Crammond -- Benchmarking Prolog for Database Applications. Thanks