How to count characters from a Java reference?

Asked

Viewed 1,994 times

3

Example I have some characters 123456789.123456789.

How to do to count up to the . after the . count again remembering that the point should not be counted.

  • string.split(".")wouldn’t it work? lenght() to see the size.

  • @Gustavocinque Good suggestion. Why not create an answer?

  • I didn’t have time @André. But now they have, so no problem.

3 answers

5


Another alternative by using indexOf():

String str = "123456789.123456789";
// Como o índice da string começa em 0, indexOf retornará exatamente o tamanho da primeira parte.
int t1 = str.indexOf('.');
int t2 = str.length() - t1 - 1; // - 1 para subtrair o "ponto" do total de caracteres da string

See working on Ideone

2

String str = "123456789.123456789";
//divide a string usando o ponto como divisor
String[] partes= str.split(".");
//antes do ponto
int n1 = partes[0].length();
//depois do ponto
int n1 = partes[1].length();

2

Another alternative that can be used is the class StringTokenizer package java.util.

public static void main (String[] args) throws java.lang.Exception{
    StringTokenizer st = new StringTokenizer("12.345.6789", ".");
    List<String> numeros = new ArrayList<String>();
    while(st.hasMoreTokens()){
        numeros.add(st.nextToken());
    }
    // Vai retornar o tamanho da 1ª sequência antes do ponto
    System.out.println(numeros.get(0).length()); 
}

Functional example in Ideone.

In terms of performance, the StringTokenizer is faster than the String#split(), however, StringTokenizer is slow compared to String#indexOf().

In the link below is shown the comparison of the performance of each alternative cited here, among others.

Browser other questions tagged

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