Showing posts with label stringutil. Show all posts
Showing posts with label stringutil. Show all posts

22 February 2011

Java: Please make best use of String.equals and equalsIgnoreCase

Al salamo Alykom,

May developers don't make the best use of java.lang.String.equals and java.lang.String.equalsIgnoreCase

Take this example:
public static CreditCart getCreditCard(String creditCardId)
{
    if (creditCardId != null && creditCardId.equalsIgnoreCase("vi"))
        return new Visa();
    else if (creditCardId != null && creditCardId.equalsIgnoreCase("mc"))
        return new MasterCard();
    else
        return new NullCard();
}

But the best use of equals and equalsIgnoreCase will make your code much compact, watch out:

public static CreditCart getCreditCard(String creditCardId)
{
    if ("vi".equalsIgnoreCase(creditCardId))
        return new Visa();
    else if ("mc".equalsIgnoreCase(creditCardId))
        return new MasterCard();
    else
        return new NullCard();
}

this is because, equalsIgnoreCase and equals returns (from Javadoc):
true if the argument is not null and it represents an equivalent String ignoring case; false otherwise

So, if the argument (in our case `creditCardId` is null, no NullPointerException will be thrown, but simple the expression will be evaluated to false!)

18 February 2011

stringutil: my c library for string utilities

Hello,

I am working on some task in CGI, I'll try to write some string utility functions to help me simplify task..

this lib is still simple, It just contains 1 non-static function `split`

#ifndef _STRING_UTIL_
#define _STRING_UTIL_

static size_t count(const char*, char);
size_t split(const char *const, const char*, char***);

#endif


#include <string.h>
#include <stdlib.h>
#include "stringutil.h"

static size_t count(const char *str, char ch)
{
    if (str == NULL) return 0;
    size_t count = 1;
    while (*str)
        if (*str++ == ch) count++;
    return count;
}

size_t split(const char *const str, const char* delim, char ***out)
{
    size_t size = count(str, *delim);
    *out = calloc(size, sizeof(char));
    char* token = NULL;
    char* tmp = (char*) str;
    int i=0;
    while ((token = strtok(tmp, delim)) != NULL)
    {
        tmp = NULL;
        (*out)[i] = (char*) malloc(sizeof strlen(token) * 4 /* to solve some bug */);
        strcpy((*out)[i++], token);
    }
    return size;
}