Monday, October 25, 2010

StringTokenizer in J2me

So in javame/ j2me StringTokenizer is also not available. I have written some utility methods for this purpose

/**
* stringTokenizer
* Tokenize the string on the basis of parmeter token
* remember empty spaces will not be return as tokens
*
* @param str String
* @param token char
* @return Vector
*/
public static Vector stringTokenizer(String str, char token)
{
/* TOKENIZE THE STRING ON THE BASIS OF THAT CHARACTER*/
Vector temp = new Vector();
str = str.trim();

char[] stringCharacters = str.toCharArray();
int j = 0;
for (int i = 0; i <>
{
if (stringCharacters[i] == token)
{
if (new String(stringCharacters, j, i - j).trim().length() > 0)
{

temp.addElement(new String(stringCharacters, j, i - j));

}
j = i + 1;

}
}
if (j <>
{
temp.addElement(new String(stringCharacters, j,
stringCharacters.length - j));
}
return temp;
}

/***************************************************************************/
/**
* stringTokenizer
* This is overloaded function of stringTokenizer it
* can tokenize on the basis of String also
* Tokenize the string on the basis of parmeter token
* remember empty spaces will not be return as tokens
*
* @param str String
* @param token char
* @return Vector
*/
public static Vector stringTokenizer(String str, String token)
{

Vector temp = new Vector();
int index;
str = str.trim();
index = str.indexOf(token);

while (index != -1)
{
if (str.substring(0, index).trim().length() > 0)
{
temp.addElement(str.substring(0, index));
}
str = str.substring(index + token.length(), str.length());
index = str.indexOf(token);

}
if (index == -1 && str.trim().length() > 0)
{
temp.addElement(str);
}

return temp;
}

/***************************************************************************/
/**
* stringTokenizerWithSpaces
* Tokenize the string on the basis of parmeter token
* here string is trimed from right side so symbol is
* included without spaces
* but empty spaces
* inside string are included as tokens
* This method specially written for the cases
* like "PSO,," Here this method return 3 tokens while
* other 'stringTokenizer(String,char)' will return only one
* @param str String
* @param token char
* @return Vector
*/
public static Vector stringTokenizerWithSpaces(String str, char token)
{
/* TOKENIZE THE STRING ON THE BASIS OF THAT CHARACTER*/
Vector temp = new Vector();
str = str.trim();

char[] stringCharacters = str.toCharArray();
int j = 0;
for (int i = 0; i <>
{
if (stringCharacters[i] == token)
{

if (i > 0)
{
temp.addElement(new String(stringCharacters, j, i - j));
}
j = i + 1;

}
}
/**
* FOR INCLUDING LAST TOKEN
* */
if (j <>
{
temp.addElement(new String(stringCharacters, j,
stringCharacters.length - j));
}
/**
* IF LAST CHARACTER IS TOKEN ITSELF THEN WE LL ADD EMPTY STRING FOR IT
* */
if (stringCharacters[stringCharacters.length - 1] == token)
{
temp.addElement("");
}
return temp;
}

No comments:

Post a Comment