Compare value at each String position in Java?

Asked

Viewed 1,261 times

4

I’m having trouble comparing a value in each position of a String, follows the example below:

parametro = "30,60,90";
private int countVirgulas(String parametro) {
    int count = 0;
    for (int i = 0; i <= parametro.length(); i++) {
        if (parametro.substring(i).equals(",")) {
            count += count;
        }
    }
    return count;
}

For example I have a String with the value "30,60,90".

I’d like to compare in every position of it and where it has a comma, and increment in the count.

In the example above the count returns me 2?

2 answers

5


The main problem seems to be the increment that is not occurring. At the moment you are adding to count own count which is initially worth 0, so it will never come out of this value. The auto-addition operator must be used with values that are not neutral, otherwise the value will not be changed. Even if it started with 1, the count would progress geometrically, which is not what is desired, each step should always add up to 1 and not the last count. It’s simpler than this, just use the increment operator that equals doing count += 1.

Another change I would make for performance issues is to take the character instead of the substring:

private int countVirgulas(String parametro) {
    int count = 0;
    for (int i = 0; i < parametro.length(); i++) {
        if (parametro.charAt(i) == ',') {
            count++;
        }
    }
    return count;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Or if you prefer:

private int countVirgulas(String parametro) {
    int count = 0;
    for (char caractere : parametro.toCharArray()) {
        if (caractere == ',') {
            count++;
        }
    }
    return count;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

If you want to use the substring() has to make a mistake, since he’s not taking one character at a time:

private int countVirgulas(String parametro) {
    int count = 0;
    for (int i = 0; i < parametro.length(); i++) {
        if (parametro.substring(i, i + 1).equals(",")) {
            count++;
        }
    }
    return count;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks bigown, in my case with the substring was not even entering the if and then I saw that put Count += Count and that was to use the Count++, using charAt(i) worked properly, thank you very much.

1

Although the question has already been answered, I would like to leave you another way to implement the comma counter using an interesting class method String how you can gain more visibility than this class can offer you.

public class ContadorDeVirgulas {

    public static void main(String[] args) {
        System.out.println(contadorDeVirgulas("30,60,90"));
    }

    public static int contadorDeVirgulas (String parametroComVirgula) {
        String[] parametroSeparado;
        int count = 0;

        //método que separa as strings de acordo com padrão que vc deseja, no seu caso, a vírgula
        parametroSeparado = parametroComVirgula.split(",", 100);

        //parametroSeparado.length retorna o tamanho do array de String após a remoção das vírgulas
        //o -1 foi usado para retirar da contagem o primeiro valor (30), pois não há vírgula antes dele
        count = parametroSeparado.length - 1;

        //retorno do contador
        return count;
    }

}

In this implementation I used the method split class String. This method splits a string into parts according to a regex (regular expression).

The code is commented, to see it in operation, see by Ideone.

For more references about this method, below are some readings that I recommend:

Java - String split() Method Source: tuturialspoint

Java documentation about the method split Source: Docs Oracle

Documentation about Regex Source: Docs Oracle

  • I would even vote for the answer if it were simpler. Just one line to do this: return parametroComVirgula.split(",").length - 1;. She is not wrong, on the contrary, but suggests an unnecessary complication. Although the intention may have been didacticism, in the end it ends up happening the opposite and people may think they need to make a huge method like this.

  • 1

    I understood, as you said, with a line it would simplify everything, I just wanted to show it that way so he could see that there are other ways in java to do it, as he is starting now to see that for a problem there are many ways to solve and tb showed some reference links where to look for extra information as he evolves in his studies.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.