Distrax
Distrax

Reputation: 15

How to check if a String contains two same characters?

In my case a string contains for example something like 2500.00. Also you input a string in the same format for example 250.0 which would be converted to 250.00. These strings will be converted to float and they will be added or subtracted.

Now I want to check if the string contains two "." somewhere for example 2.50.00 or 250..00. In that case an errormessage should be displayed.

Therefore my question is how am I able to check if a string contains two "." characters at any position of the string?

Upvotes: 1

Views: 1210

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627272

You may check if a dot appears more than once in a string with a simple method checking if the first index of the char is not equal to the index of the last char occurrence:

boolean containsTwoDots(String str) { 
    return str.indexOf('.') != str.lastIndexOf('.'); 
}

Upvotes: 1

Related Questions