How can I check how many "@" has in a String?
example:
"@ Testing"
It has 2 @
, how can I do this check in java?
How can I check how many "@" has in a String?
example:
"@ Testing"
It has 2 @
, how can I do this check in java?
Using java 8:
String testString = "@Teste @Teste@ a@A";
long a = testString.chars().filter(ch -> ch =='@').count();
System.out.println(a);
Result:
4
See it working: link
In this SOEn response there are several other ways to do this.
There are many ways to do this:
Using Apache Commons :
String text = "@Teste @Teste";
int apache = StringUtils.countMatches(text, "@");
System.out.println("apache = " + apache);
Using Replace :
int replace = text.length() - text.replace("@", "").length();
System.out.println("replace = " + replace);
Using ReplaceAll (case 1):
int replaceAll = text.replaceAll("[^@]", "").length();
System.out.println("replaceAll (caso 1) = " + replaceAll);
Using ReplaceAll (case 2):
int replaceAllCase2 = text.length() - text.replaceAll("\@", "").length();
System.out.println("replaceAll (caso 2) = " + replaceAllCase2);
Using Split :
int split = text.split("\@",-1).length-1;
System.out.println("split = " + split);
Among others, see here .
You can use the countMatches
method of class StringUtils
of package org.apache.commons.lang3
:
int count = StringUtils.countMatches("@Teste @Teste", "@");