Question:
I have a String where I store a string of numbers with a + sign before the number. What I want is to be able to count how many + signs there are, in order to know how many numbers and signs there are in the string.
For example:
String cadenanumeros = "+0+4+3+4+5";
Signos+ = 5;
I hope you can help me, in advance, thank you very much for your help and time!
Answer:
There are at least 7 ways to do this with native Java code, aside from some library-based solutions provided in other answers.
I show you here those 7 ways with pure Java:
We will define our test chain:
String testString = "+0+4+3+4+5";
1. con replace
:
int replace = testString.length() - testString.replace("+", "").length();
System.out.println("1. Con replace = " + replace);
2. Con replaceAll
:
int replaceAll = testString.replaceAll("[^+]", "").length();
System.out.println("2. Con replaceAll = " + replaceAll);
3. With replaceAll
(2º case):
int replaceAllCase2 = testString.length() - testString.replaceAll("\\+", "").length();
System.out.println("3. Con replaceAll (2º caso) = " + replaceAllCase2);
4. Con split
:
int split = testString.split("\\+",-1).length-1;
System.out.println("4. Con split = " + split);
5. With lambda expressions (as of Java 8):
long java8 = testString.chars().filter(ch -> ch =='+').count();
System.out.println("5. Con Lambda (Java8) = " + java8);
6. With lambda expressions (2nd case):
long java8Case2 = testString.codePoints().filter(ch -> ch =='+').count();
System.out.println("6. Con Lambda (2º caso) = " + java8Case2);
7. Con stringTokenizer
:
int stringTokenizer = new StringTokenizer(" " +testString + " ", "+").countTokens()-1;
System.out.println("7. Con stringTokenizer = " + stringTokenizer);
Exit:
1. Con replace = 5
2. Con replaceAll = 5
3. Con replaceAll (2º caso) = 5
4. Con split = 5
5. Con Lambda (Java8) = 5
6. Con Lambda (2º caso) = 5
7. Con stringTokenizer = 5
show
Here you can see a DEMO IN RETTESTER
Fountain
The most popular answer to the Java question: How do I count the number of occurrences of a char in a String? on Stackoverflow in English.