implement lastIndexOf

This commit is contained in:
XenoAmess 2020-06-01 02:26:14 +08:00 committed by Rob Tompkins
parent dee8f6fb84
commit 217da1e6aa
2 changed files with 25 additions and 29 deletions

View File

@ -266,22 +266,33 @@ public class CharSequenceUtils {
start = len1 - len2;
}
if (check(cs, searchChar, len2, start)) {
return start;
}
for (int i = start - 1; i >= 0; i--) {
if (check(cs, searchChar, len2, i)) {
return i;
}
}
char char0 = searchChar.charAt(0);
int i = start;
while (true) {
while (cs.charAt(i) != char0) {
i--;
if (i < 0) {
return -1;
}
}
if (checkLaterThan1(cs, searchChar, len2, i)) {
return i;
} else {
i--;
if (i < 0) {
return -1;
}
}
}
}
private static boolean check(final CharSequence cs, final CharSequence searchChar, int len2, int start1) {
for (int i = 0; i < len2; i++) {
if (cs.charAt(start1 + i) != searchChar.charAt(i)) {
private static boolean checkLaterThan1(final CharSequence cs, final CharSequence searchChar, int len2, int start1) {
for (int i = 1, j = len2 - 1; i <= j; i++, j--) {
if (cs.charAt(start1 + i) != searchChar.charAt(i)
||
cs.charAt(start1 + j) != searchChar.charAt(j)
) {
return false;
}
}

View File

@ -16,23 +16,14 @@
*/
package org.apache.commons.lang3;
import static java.nio.CharBuffer.wrap;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.nio.CharBuffer;
import java.util.Random;
import java.util.stream.IntStream;
import org.apache.commons.lang3.text.StrBuilder;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests CharSequenceUtils
@ -269,14 +260,8 @@ public class CharSequenceUtilsTest {
}
private void testNewLastIndexOfSingleSingle(CharSequence a, CharSequence b, int start) {
int expected = a.toString().lastIndexOf(b.toString(), start);
// assertEquals(
// expected,
// lastIndexOf(new WrapperString(a), b, start),
// "testNewLastIndexOf fails! original : " + a + " seg : " + b + " start : " + start
// );
assertEquals(
expected,
a.toString().lastIndexOf(b.toString(), start),
CharSequenceUtils.lastIndexOf(new WrapperString(a.toString()), b.toString(), start),
"testNewLastIndexOf fails! original : " + a + " seg : " + b + " start : " + start
);