Verify that you have more than one character in a String

7

How can I check how many "@" has in a String?

example:

  

"@ Testing"

It has 2 @ , how can I do this check in java?

    
asked by anonymous 07.03.2017 / 01:29

3 answers

9

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.

    
07.03.2017 / 01:36
6

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 .

    
07.03.2017 / 01:45
3

You can use the countMatches method of class StringUtils of package org.apache.commons.lang3 :

int count = StringUtils.countMatches("@Teste @Teste", "@");
    
07.03.2017 / 01:36