Sunday, January 24, 2010

J2ME String Split Method


private String[] split(String _text, String _separator) {
Vector nodes = new Vector();
// Parse nodes into vector
int index = _text.indexOf(_separator);

while (index >= 0) {
nodes.addElement(_text.substring(0, index));
_text = _text.substring(index + _separator.length());
index = _text.indexOf(_separator);
}
// Get the last node
nodes.addElement(_text);

// Create splitted string array
String[] result = new String[nodes.size()];
if (nodes.size() > 0) {
for (int loop = 0; loop < nodes.size(); loop++) {
result[loop] = (String) nodes.elementAt(loop);
System.out.println(result[loop]);
}
}
return result;
}

J2ME String Replace Method

J2ME doesn't have a replace method so you can use the code below. I found this function/method at http://www.itgalary.com/forum_posts.asp?TID=871 . I hope that you can use it too.


public static String replace(String _text, String _searchStr, String _replacementStr) {
// String buffer to store str
StringBuffer sb = new StringBuffer();

// Search for search
int searchStringPos = _text.indexOf(_searchStr);
int startPos = 0;
int searchStringLength = _searchStr.length();

// Iterate to add string
while (searchStringPos != -1) {
sb.append(_text.substring(startPos, searchStringPos)).append(_replacementStr);
startPos = searchStringPos + searchStringLength;
searchStringPos = _text.indexOf(_searchStr, startPos);
}

// Create string
sb.append(_text.substring(startPos,_text.length()));

return sb.toString();
}