0

How check if a String contains only one specific character? Eg:

On the String square/retrofit and square/retrofit/issues I need to check if the String has more than one / character.

square/retrofit/issues need to be false because have more than one / character and square/retrofit need to be true.

The string can have numbers.

2 Answers 2

2

You do not need regex. Simple indexOf and lastIndexOf methods should be enough.

boolean onlyOne = s.indexOf('/') == s.lastIndexOf('/');

EDIT 1
Of course, if / does not appear in given string above will be true. So, to avoid this situation you can also check what is returned index from one of these methods.

EDIT 2
Working solution:

class Strings {
    public static boolean availableOnlyOnce(String source, char c) {
        if (source == null || source.isEmpty()) {
            return false;
        }

        int indexOf = source.indexOf(c);
        return (indexOf == source.lastIndexOf(c)) && indexOf != -1;
    }
}

Test cases:

System.out.println(Strings.availableOnlyOnce("path", '/'));
System.out.println(Strings.availableOnlyOnce("path/path1", '/'));
System.out.println(Strings.availableOnlyOnce("path/path1/path2", '/'));

Prints:

false
true
false
Sign up to request clarification or add additional context in comments.

Comments

0

Or if you'd like to use a bit more modern approach with streams:

boolean occursOnlyOnce(String stringToCheck, char charToMatch) {
    return stringToCheck.chars().filter(ch -> ch == charToMatch).count() == 1;
}

Disclaimer: This is not supposed to be the most optimal approach.

A bit more optimized approach:

    boolean occursOnlyOnce(String stringToCheck, char charToMatch) {
    boolean isFound = false;
    for (char ch : stringToCheck.toCharArray()) {
        if (ch == charToMatch) {
            if (!isFound) {
                isFound = true;
            } else {
                return false; // More than once, return immediately
            }
        }
    }
    return isFound; // Not found
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.