Check if you have more than one character in a String

Asked

Viewed 160 times

7

How can I check how many "@" you have in a string?

example:

"@Teste @Teste"

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

3 answers

9


Using java 8:

String testString =  "@Teste @Teste@ a@A";
long a = testString.chars().filter(ch -> ch =='@').count();
System.out.println(a);

Upshot:

4

See working: https://ideone.com/bbaLdF

In this reply from Soen there are several other ways to do this.

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.

3

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

int count = StringUtils.countMatches("@Teste @Teste", "@");

Browser other questions tagged

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