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.
You can pass a negative value to String.split(String, int)
like
String str = "aaa,,bbb,,ccc,";
String[] strArray = str.split(",", -1);
System.out.println(Arrays.toString(strArray));
Output is
[aaa, , bbb, , ccc, ]
This is helpfully documented in the linked javadoc as,
If n is non-positive then the pattern will be applied as many times as possible and the array can have any length
Edit
public static void main(String[] args) {
String str = "aaa,,bbb,,ccc,";
String[] strArray = str.split(",", -1);
for (int i = 0; i < strArray.length; i++) {
if (strArray[i].isEmpty()) {
strArray[i] = null;
}
}
System.out.println(Arrays.toString(strArray));
}
Output is
[aaa, null, bbb, null, ccc, null]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments