J2ME Split String code segment

Most of you who are used to the split() functionality may miss it a lot when moving on to J2ME. So, here is a code segment which I had used to acchive similar functionality using J2ME methods.

public String[] split(String str, String delimiter){

//Iterate through the text to get the count of occurences
//This is done since we do not know how many times the
//delimitter occurs in the given string
//--------------------------------------------------//

int delimiterCount=0;
int index;
String tmpStr=str;

String[] splittedList;

while((index=tmpStr.indexOf(delimiter))!=-1){

tmpStr=tmpStr.substring(index+delimiter.length());
delimiterCount++;
}

splittedList=new String[delimiterCount];

/*-----------------------------------------------*/


/*-----------------------------------------------*/


//-----------------------------------------------//
index=0;
int counter=0;
tmpStr=str;


while((index=tmpStr.indexOf(delimiter))!=-1){


int nextIndex=tmpStr.indexOf(delimiter, index+1);

if(nextIndex!=-1){
splittedList[counter++]=tmpStr.substring(index+delimiter.length(), nextIndex);
tmpStr=tmpStr.substring(nextIndex);

}else{
splittedList[counter++]=tmpStr.substring(index+delimiter.length());
tmpStr=tmpStr.substring(index+1);
}
}

return splittedList;
}

Happy coding !!!!

Comments

shan said…
very very happpy thanks!..
Mehmet said…
We can also use this code.


private int[] setRule(String ruleId){
String regRule = getRule(ruleId);
char[] charRule = regRule.toCharArray();
int[] arrayRule = new int[2];
StringBuffer bufRule = new StringBuffer();
int m = 0;
for (int i = 0; i < charRule.length; i++) {
if (":".indexOf(charRule[i]) != -1) {
arrayRule[m] = Integer.parseInt(bufRule.toString());
bufRule.setLength(0);
m++;
} else {
bufRule.append(charRule[i]);
}
}
arrayRule[m] = Integer.parseInt(bufRule.toString());
return arrayRule;
}
ruchira said…
Thank you friend !!!
Unknown said…
Thank u so much,it helped me a lot.........
Unknown said…
Hi all,
First thanks for the code
the Java Split() function accepts regular expression as input
If we want to split "foo.mas.kjh.lok" with "." we should call it as "\\."

But if we give ("\\.") as delimeter in j2me result wont be same. Can any one suggest how can we achieve same behavior in J2me
Please suggest

Thanks,
Chandu
ruchira said…
Hi Chandra,

Yes, that may be a feature of Java SE which is not available on J2ME. I don't think this will work in my code since I use a different logic to split the strings. If you are using my code, then I recommend you to set the delimiter as "." only.
Hope that helps.

Popular posts from this blog

Encrypt and Decrypt Images Using Java

Build your own Network sniffer

ASP Response.Write newline