Reputation: 1759
String class has the method contains(CharSequence s)
that returns true if and only if the string contains the specified sequence of char values.
I need to replace one char from a string, but before this action, I have to validate if the string contains the specific char.
I know that char operations as indexOf
and replace
are more efficient than the String equivalents.
So I created a helper method to know if the String contains the specific char as :
boolean contains(String str, char c) {
int notFound = -1;
return str.indexOf(c) != notFound;
}
This method is more efficient than contains(CharSequence s)
method of String.
My question:
What is the most performant way to know if a String contains one specific char without losing readability?
Upvotes: 0
Views: 137
Reputation: 1042
This is a quite general question, so the answer will be too
As @F43nd1r pointed out, “best” is a vague term here. Assuming best is measured in reasonable according to readability, maintainability and performance, it strongly depends on the possible character set of your string and its length. The method
str.indexOf(ch)>=0
of @khelwood is surely the best for common short strings, However it has O(n) complexity with n
being the amount of chars in your string.
If you need to query the same string several times for different characters AND it is quite big AND the possible character set is limited enough you might want do trade readability for performance:
char minChar='0';
BitSet b = new BitSet();
for (char c : string) {
b.set(c-minChar);
}
Now you can query this BitSet whether a certain bit is set quite fast.
Upvotes: 3