Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a String contains the same letter more than once?

Tags:

java

string

I'm a bit confused in how I would check if a String contains the same letter more than once.

ArrayList<String> words = new ArrayList<String>();

words.add("zebra");
words.add("buzzer");
words.add("zappaz");

Let's say I only want to print out any words which contain more than one "z", therefore only "buzzer" and "zappaz" would get printed. How would I do this?

like image 481
rednaxela Avatar asked Nov 30 '22 22:11

rednaxela


2 Answers

To test if a string contains two z, you can do this :

 boolean ok = word.matches(".*z.*z.*")
like image 175
Denys Séguret Avatar answered Dec 06 '22 09:12

Denys Séguret


indexOf returns the... index of... a character in a string. It also takes an optional argument specifying where to search. If there is no match, it returns -1. So just use it twice:

s.indexOf(letter, s.indexOf(letter) + 1) > -1

It works!

(For efficiency's sake, though, may as well check the first result.)

like image 39
Ry- Avatar answered Dec 06 '22 11:12

Ry-