目录
1 startsWith:从源串指定下标开始,是否以目标字符串开头
1.1 源码
// prefix 目标串
// toffset 源串指定开始下标
public boolean startsWith(String prefix, int toffset) {
char ta[] = value;
int to = toffset;
char pa[] = prefix.value;
int po = 0;
int pc = prefix.value.length;
// 如果源串指定开始下标小于0,或者大于源串长度与目标串长度的差值,直接返回false
if ((toffset < 0) || (toffset > value.length - pc)) {
return false;
}
while (--pc >= 0) {
// 但凡有一个字符不相等,直接返回false
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
2 endsWith:是否以目标字符串结束
2.1 源码
// 如果理解了startsWith(),理解这就很简单了
public boolean endsWith(String suffix) {
return startsWith(suffix, value.length - suffix.value.length);
}
3 matches:字符串是否匹配正则表达式
3.1 源码
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
3.2 Pattern.matches方法实际上是使用了Pattern和Matcher类,这两个类比较难理解,就不往下分析了
public static boolean matches(String regex, CharSequence input) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}
3.3 Pattern
public static final int UNICODE_CHARACTER_CLASS = 0x100;
public static final int UNICODE_CASE = 0x40;
public static Pattern compile(String regex) {
return new Pattern(regex, 0);
}
private Pattern(String p, int f) {
pattern = p;
flags = f;
// to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present
if ((flags & UNICODE_CHARACTER_CLASS) != 0)
flags |= UNICODE_CASE;
// Reset group index count
capturingGroupCount = 1;
localCount = 0;
if (pattern.length() > 0) {
compile();
} else {
root = new Start(lastAccept);
matchRoot = lastAccept;
}
}
3.3 Matcher
public boolean matches() {
return match(from, ENDANCHOR);
}
boolean match(int from, int anchor) {
this.hitEnd = false;
this.requireEnd = false;
from = from < 0 ? 0 : from;
this.first = from;
this.oldLast = oldLast < 0 ? from : oldLast;
for (int i = 0; i < groups.length; i++)
groups[i] = -1;
acceptMode = anchor;
boolean result = parentPattern.matchRoot.match(this, from, text);
if (!result)
this.first = -1;
this.oldLast = this.last;
return result;
}