@Test
public void shouldContainsSecondValueInFirstValue() {
String firstValue = "O pikap, su pikap, bu pikap.";
String secondValue = "pikap";
int actual = contains(firstValue, secondValue);
Assert.assertThat(actual, is(22));
}
@Test
public void shouldNotContainsSecondValueInFirstValue() {
String firstValue = "O pikap, su pikap, bu pikap.";
String secondValue = "pikapci";
int actual = contains(firstValue, secondValue);
Assert.assertThat(actual, is(-1));
}
@Test
public void shouldNullSecondValueInFirstValue() {
String firstValue = "O pikap, su pikap, bu pikap.";
String secondValue = null;
int actual = contains(firstValue, secondValue);
Assert.assertThat(actual, is(-1));
}
primitive contains method ;
private int contains(String firstValue, String secondValue) {
int index = -1;
if (firstValue == null || secondValue == null) {
return index;
}
final boolean isContainsAny = containsAny(firstValue, toCharArray(secondValue));
if (!isContainsAny) {
return index;
}
index = firstValue.indexOf(secondValue);
while (index >= 0) {
int lastIndex = index;
index = firstValue.indexOf(secondValue, index + 1);
if (index == -1) {
return lastIndex;
}
}
return index;
}
public static boolean containsAny(CharSequence cs, char... searchChars) {
if (!isEmpty(cs) && !isEmpty(searchChars)) {
int csLength = cs.length();
int searchLength = searchChars.length;
int csLast = csLength - 1;
int searchLast = searchLength - 1;
for (int i = 0; i < csLength; ++i) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLength; ++j) {
if (searchChars[j] == ch) {
if (!Character.isHighSurrogate(ch)) {
return true;
}
if (j == searchLast) {
return true;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return true;
}
}
}
}
return false;
} else {
return false;
}
}
public static boolean isEmpty(char[] array) {
return array == null || array.length == 0;
}
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
static char[] toCharArray(CharSequence cs) {
if (cs instanceof String) {
return ((String) cs).toCharArray();
} else {
int sz = cs.length();
char[] array = new char[cs.length()];
for (int i = 0; i < sz; ++i) {
array[i] = cs.charAt(i);
}
return array;
}
}