开发者

String replace in Java ME double space

How can I replace "a  b" by "a b" in Java ME?

Th开发者_Python百科e replace() method doesn't accept Strings, but only characters. And since a double space contains two characters, I think I have a small problem.


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;
    }
}


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();
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜