views:

328

answers:

2

How can I replace this "a  b" by "a b" in j2me?

the replace() method doesn't accept Strings, but only chars. And since a double space contains two chars, I think i have a small problem.

A: 

Here's one function you might use:

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();
} 
Darin Dimitrov
Thanks, I was hoping there was an shorter solution.Why are you using these underscores? to indicate variables are parameters?
hsmit
It's a good coding standard to name variables differently based on their scope. Google's Android code uses an 'm' prefix for instance variables. Symbian uses an 'i' prefix for instance and an 'a' prefix for method parameters.
QuickRecipesOnSymbianOS
+1  A: 

What do you think of this one? I tried one myself.

private String replace(String needle, String replacement, String haystack) {
    String result = "";
    int index = haystack.indexOf(needle);
    if(index==0) {
        result = replacement+haystack.substring(needle.length());
        return replace(needle, replacement, result);
    }else if(index>0) {
        result = haystack.substring(0,index)+ replacement +haystack.substring(index+needle.length());
        return replace(needle, replacement, result);
    }else {
        return haystack;
    }
}
hsmit