Monday, April 23, 2012

Welcome & replace char

Hi Guys.

My first post to this blog. Its all about Android & Java coding.
I will post some code snippets that could be handy.

When dealing with my Android application 'Wordlist Pro 2.x' I was forced to do a lot of speed optimization to make it the fastest dictionary search engine. I'm not sure its the fastest one, but at least damn close. I will post some code examples in this blog.

Here are a few (common tasks) static helper functions.

Replace First Character (String)
    public static String replaceFirst(String in, char findChar, CharSequence replaceChar){

        StringBuilder input = new StringBuilder(in);
        char c = input.charAt(0);
        if( findChar == c )
            input.replace(0, 1, (String) replaceChar);
        return input.toString();

    }

Replace Last Character (String)

    public static String replaceLast(String in, char findChar, CharSequence replaceChar){

        StringBuilder input = new StringBuilder(in);
        int len = input.length();
        int pos = len-1;
        char c = input.charAt(pos);
        if( findChar == c )
            input.replace(pos, pos+1, (String) replaceChar);
        return input.toString();

    }

Remove First Character (StringBuilder)

    public static StringBuilder removeFirst(StringBuilder input, char removeChar){

        int pos = 0;
        int len = input.length();
        char c;
        for( ; pos < len ; pos++ ){
            c = input.charAt(pos);
            if( removeChar == c ){
                input.replace(pos, pos+1, "");
                break;
            }
        }
        return input;

    }


Remove HTML tags from string
public static String removeHTMLTags(String in){
in = in.replaceAll("<(?:\"[^\"]*\"[\'\"]*|\'[^\']*\'[\'\"]*|[^\'\">])+>", ""); return in; }

Use at will (Ctrl+c, Ctrl+v).

/rob

No comments:

Post a Comment