The following code block shows how to split a string in to array of strings in blackberry.
private String[] split(String strString, String strDelimiter) { String[] strArray; int iOccurrences = 0; int iIndexOfInnerString = 0; int iIndexOfDelimiter = 0; int iCounter = 0; //Check for null input strings. if (strString == null) { throw new IllegalArgumentException("Input string cannot be null."); } //Check for null or empty delimiter strings. if (strDelimiter.length() <= 0 || strDelimiter == null) { throw new IllegalArgumentException("Delimeter cannot be null or empty."); } if (strString.startsWith(strDelimiter)) { strString = strString.substring(strDelimiter.length()); } //If strString does not end with the delimiter then add it //to the string in order to comply with the desired format. if (!strString.endsWith(strDelimiter)) { strString += strDelimiter; } //Count occurrences of the delimiter in the string. //Occurrences should be the same amount of inner strings. while((iIndexOfDelimiter = strString.indexOf(strDelimiter, iIndexOfInnerString)) != -1) { iOccurrences += 1; iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length(); } //Declare the array with the correct size. strArray = new String[iOccurrences]; //Reset the indices. iIndexOfInnerString = 0; iIndexOfDelimiter = 0; //Walk across the string again and this time add the //strings to the array. while((iIndexOfDelimiter = strString.indexOf(strDelimiter, iIndexOfInnerString)) != -1) { //Add string to array. strArray[iCounter] = strString.substring(iIndexOfInnerString,iIndexOfDelimiter); //Increment the index to the next character after //the next delimiter. iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length(); //Inc the counter. iCounter += 1; } return strArray; }//fn split
To make the function call
String delimit = ","; String mainStr = "apple, banana, orange, pineapple, cherry"; String[] fruits = split(mainStr , delimit);
Comments on: "How to split a string in to array of strings in Blackberry" (6)
such an useful article for developers programmers and designers alike
Glad u liked my post and found it useful.
[…] The following code block shows how to split a string in to array of strings in blackberry. [/sourcecode] private String[] split(String strString, String strDelimiter) { String[] strArray; int iOccurrences = 0; int iIndexOfInnerString = 0; int iIndexOfDelimiter = 0; int iCounter = 0; //Check for null input strings. if (strString == null) { throw new IllegalArgumentException("Input string cannot be null."); } //Check for nu … Read More […]
Was looking for a long time. Thanks. I just wondering why RIM never got the method in API’s…
YeP this split is great…
Thanks
katharnavas
if you send a null delimiter, when your code try do
strDelimiter.length()
in
if (strDelimiter.length() 0.
Excuse me, i speak spanish and my english is not good.