JAVA源码String学习

时间:2023-02-26 08:28:53

String 内部是用char数组存储数据,主要就是对这三个属性进行操作。

 /** The value is used for character storage. */
private final char value[];

/** The offset is the first index of the storage that is used. */
private final int offset;

/** The count is the number of characters in the String. */
private final int count;


indexOf函数

import java.util.HashMap;
import java.util.Map;

public class App {
public static void main(String[] args) {
String str = new String("dddasdadad");
char[] strChar = str.toCharArray();
String str1 = new String("ad");
char[] str1Char = str1.toCharArray();
int result = indexOf(strChar, 0, 9, str1Char, 0, 2, 0);
System.out.println(result);
}




static int indexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount, int fromIndex) {
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}


char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);


for (int i = sourceOffset + fromIndex; i <= max; i++) {
/*找到目标数组的第一个字符在原字符数组中第一次出现的位置 */
if (source[i] != first) {
while (++i <= max && source[i] != first) ; //此处写法可学习
}


/* 通过上面的while循环找到第一次出现的位置后,循环对比目标数组剩下的字符是否和原字符数组相对位置的相同 */
if (i <= max) {
int j = i + 1; //4
int end = j + targetCount - 1; //5
for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++); //此处写法可学习


if (j == end) {
/* 因为上面会j++,所以若相同则找到全部字符数组,返回第一次出现的位置i. */
return i - sourceOffset;
}
}
}
return -1;
}


}



 

lastIndexOf函数

public class App {
public static void main(String[] args) {
String str = new String("dddasdadad");
char[] strChar = str.toCharArray();
String str1 = new String("da");
char[] str1Char = str1.toCharArray();
System.out.println(lastIndexOf(strChar, 0, 10, str1Char, 0, 2,5));
}

static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount, int fromIndex) {
/*
* Check arguments; return immediately where possible. For consistency,
* don't check for null str.
*/
int rightIndex = sourceCount - targetCount;
if (fromIndex < 0) {
return -1;
}
if (fromIndex > rightIndex) {
fromIndex = rightIndex;
}
/* 空字符串也匹配 */
if (targetCount == 0) {
return fromIndex;
}

/* 目标数组最后一个元素在数组的位置 */
int strLastIndex = targetOffset + targetCount - 1;
/* 目标数组最后一个元素*/
char strLastChar = target[strLastIndex];
/* 原数组最后一个需要校验的位置*/
int min = sourceOffset + targetCount - 1;
/* 原数组开始校验的位置*/
int i = min + fromIndex;

startSearchForLastChar: while (true) { /*此处可学习*/
/* 从原数组最后一位数找到目标数组最后一位第一次出现的位置 i */
while (i >= min && source[i] != strLastChar) {
i--;
}
if (i < min) {
return -1;
}
int j = i - 1;
int start = j - (targetCount - 1);
int k = strLastIndex - 1;
/* 原数组和目标数组剩下的位置字符一一对比,若不相同则将i-1跳至上面继续执行 */
while (j > start) {
if (source[j--] != target[k--]) {
i--;
continue startSearchForLastChar;
}
}
return start - sourceOffset + 1;
}
}
}