Jacek Kwiecień
Jacek Kwiecień

Reputation: 12637

counting letters and spaces

I need to count letters and spaces in some string. output is the string of mine

I tried this:

    for (int i = 0; i < output.length(); i++) {
        if (output.charAt(i) != ' ') {
            letters = letters++;
        } //counting spaces
        else {
            spaces = spaces++;
        }

It doesn't work. I get 0 letters and 0 spaces. I suppose I need some code instead ' ', right?

Upvotes: 1

Views: 306

Answers (4)

codaddict
codaddict

Reputation: 454970

letters = letters++;

should be

letters++;

because letters = letters++;

is equivalent to,

int temp = letters;
letters++;
letters = temp;

which does not increment the value of letters

This classic Q/A of SO has more insights

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

The java Character class has helper methods that you could use:

int letters = 0, spaces = 0;
for (int i = 0; i < output.length(); i++)
{
    char c = output.charAt(i);
    if (Character.isLetter(c))
    {
        letters++;
    }
    else if (Character.isWhitespace(c))
    {
        spaces++;
    }
}

Upvotes: 0

Mat
Mat

Reputation: 206689

letters = letters++;

is wrong. (Same for spaces.) See here or here for an explanation: letters is unchanged after that line.

Either use:

letters = letters + 1;

or simply:

letters++;

Upvotes: 5

KV Prajapati
KV Prajapati

Reputation: 94645

Use Character.isSpaceChar and Character.isLetter method. (documentation)

Upvotes: 1

Related Questions