Friday 13 July 2012

Get words or characters from a string Java

Get all the words in a string in a simple java program.

  public List  getWords(String line)
    {

     char delimiter = ' ';
     StringTokenizer tokenizer = new StringTokenizer(line, delimiter );
     if ( tokenizer == null )
            return null;

     List result = new ArrayList();

     while ( tokenizer.hasMoreTokens() )
           result.add(tokenizer.nextToken());

     return result;
    }


Count number of Characters in a word

public static int countCharacters(String str)
    {
        int charCount = 0;

        if ( str == null || str.trim().isEmpty() )
            return charCount;

        int length = str.length();
        for ( int i = 0; i < length; i++ )
        {
            if ( str.charAt(i) != ' ' )
                charCount++;
        }
        return charCount;
    }


public static void main(String[] args)
{
        String word = "LI FE";
        System.out.println("Number of characters in '" + word + "' = " + countCharacters(word));

}

No comments:

Post a Comment