The performance of regular expressions in Java is compared with that of indexof

Please tell me how to match "" And period "." It is also more effective to use indexof () instead of regular expression to excite once in a string

String s= "Hello_Wor.ld"  or 
s="12323_!£££$.asdfasd"

Basically, no character can appear in_ And before and after The only requirement is that the entire string should contain only one_ The emergence of and

Solution

Indexof will be much faster than regular expressions and may also be easier to understand

Only test indexof ('' ') > = 0, and then test indexof (' ', indexoffirstunderscore) < 0 Do the same thing in the meantime

private boolean containsOneAndOnlyOne(String s,char c) {
    int firstIndex = s.indexOf(c);
    if (firstIndex < 0) {
        return false;
    }
    int secondIndex = s.indexOf(c,firstIndex + 1);
    return secondIndex < 0;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>