Java String count shared characters between two String values
//package com.demo2s; public class Main { public static void main(String[] argv) throws Exception { String str = "demo2s.com demo2s.com"; String chars = "com"; System.out.println(numSharedChars(str, chars)); }/* w w w . ja va 2 s . co m*/ /** * Counts the number of (not necessarily distinct) characters in the * string that also happen to be in 'chars' */ public static int numSharedChars(final String str, final String chars) { if (str == null || chars == null) { return 0; } int total = 0, pos = -1; while ((pos = indexOfChars(str, chars, pos + 1)) != -1) { total++; } return total; } /** * Like String.indexOf() except that it will look for any of the * characters in 'chars' (similar to C's strpbrk) */ public static int indexOfChars(String str, String chars, int fromIndex) { final int len = str.length(); for (int pos = fromIndex; pos < len; pos++) { if (chars.indexOf(str.charAt(pos)) >= 0) { return pos; } } return -1; } /** * Like String.indexOf() except that it will look for any of the * characters in 'chars' (similar to C's strpbrk) */ public static int indexOfChars(String str, String chars) { return indexOfChars(str, chars, 0); } }