I have two classes Reader and Tokenizer. I want to split Strings in Wlist Arraylist from the Reader class in tokenizer class. Splitting must be done based on odd and even length of the String.
Ex: If string is "teacher", as its length is odd it should be split into three parts "te", "ac", "her".
If string is even like "cattle" it should be split in 3 parts "ca", "tt", "le".
Reader Class
import java.util.ArrayList;
import java.util.List;
public class Reader {
String[] wordList = {"Printer", "Airport", "Painter", "Letter",
"vehicle", "Teacher"};
String[] SentenceList = {"Device made to waste ink and paper","Platform for Commercial air transport",
"Someone who uses colors and brushes","a written type of communication sent by mail",
"Thing used to travel via land","A person who teaches"};
ArrayList<String> Wlist = new ArrayList<>(6);
public ArrayList<String> wordCheck(){
for(int i=0;i<6;i ){
if((wordList[i] != null) && (!wordList[i].equals("")) && (wordList[i].matches("^[a-zA-Z]*$"))
&& (wordList[i].length()>4)) {
//System.out.println("Array does satisfy the required criteria");
Wlist.add(wordList[i].toUpperCase());
}
else
{
System.out.println("Array does NOT satisfy the required criteria");
break;
}
}
//System.out.println(Wlist);
return Wlist;
}
public ArrayList<String> getWord(){
return wordCheck();
}
public ArrayList<String> Sentence(){
ArrayList<String> Slist = new ArrayList<>(6);
for(int i=0;i<6;i ){
Slist.add(SentenceList[i]);
}
//System.out.println(Slist);
return Slist;
}
}
// This is the updated Tokenizer class
import java.util.ArrayList;
import java.util.List;
public class Tokenizer {
Reader rd = new Reader();
ArrayList<String> SplList = new ArrayList<>();
public ArrayList<String> splitString() {
ArrayList<String> Wlist = rd.getWord();
//String[] result = new String[(Wlist.get().length() 2)/3];
for(int i=0;i<Wlist.size();i ){
SplList.add(Arrays.toString(Wlist.get(i).split("(?<=\\\\G..)(?=..)")));
}
System.out.println(SplList);
return SplList;
}
}
CodePudding user response:
If you're asking how to split a string into pairs of letters, with any remainder left with the last split:
String[] parts = str.split("(?<=\\G..)(?=..)");
which achieves your goal (see below).
The split matches between these two look arounds:
(?<=\\G..)
two chars after the end of the last match(?=..)
there are (at least) two chars after
String[] wordList = {"Printer", "Airport", "Painter", "Letter", "vehicle", "Teacher"};
List<String[]> splitWords = Arrays.stream(wordList).map(s -> s.split("(?<=\\G..)(?=..)")).collect(toList());
splitWords.forEach(a -> System.out.println(Arrays.toString(a)));
Output:
[Pr, in, ter]
[Ai, rp, ort]
[Pa, in, ter]
[Le, tt, er]
[ve, hi, cle]
[Te, ac, her]