I have below code
String str= new String("aaa,,bbb,,ccc,");
String[] strArray= str.split(",");
From this I am getting below values in strArray
strArray = [aaa,'',bbb,'',ccc];
But I want below output
strArray = [aaa,null,bbb,null,ccc,null];
I have written my own function to do this, but I want to know is there any standard method which can give this output?
If yes then please suggest
If no then please suggest if any improvement for below code.
public List<String> splitStr(String str, char character) {
List<String> list = null;
if (StringUtil.isNotEmpty(str)) {
list = new ArrayList<String>();
int i;
char ch;
int characterIndex, loopStartingIndex = 0;
if (str.charAt(0) == character) {
list.add(null);
} else {
list.add(str.substring(0, str.indexOf(character)));
loopStartingIndex = str.indexOf(character);
}
int length = str.length();
for (i = loopStartingIndex; i < length; i++) {
ch = str.charAt(i);
if (ch == character) {
characterIndex = str.indexOf(character, i+1);
if (characterIndex == i+1 || characterIndex == -1) {
list.add(null);
} else {
list.add(str.substring(i+1, characterIndex));
i = characterIndex-1;
}
}
}
}
/*for (String s : list) {
System.out.println(s);
}*/
return list;
}
Edit:
I had tested the code for abc,,,,
string with str.split(",")
method and I got [abc]
as output so I thought aaa,,bbb,,ccc
will give me 3 values by split method. But it is giving [aaa,'',bbb,'',ccc]
skipping ending commas.