Example I have some character 123456789.123456789 .
How to count to .
after .
count again remembering that the point should not be counted.
Example I have some character 123456789.123456789 .
How to count to .
after .
count again remembering that the point should not be counted.
Another alternative 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 at Ideone
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();
Another alternative that can be used is the class StringTokenizer
of the java.util
package.
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, StringTokenizer
is faster than String#split()
", however, StringTokenizer
is slow when compared to String#indexOf()
.
The link below shows the performance comparison of each of the alternatives mentioned here, among others.