• 无论是功能性代码还是算法性代码,程序都是一系列流程的合集
    • 既然是流程就分为:一般流程和异常流程;
    • 一般流程保证了基本功能;
    • 异常流程则是对程序稳定性的保证,不能因为一些非法输入,项目就挂了;
  • 注意,布尔表达式的先后顺序,有时不可以交换

    if (null == instance || instance.isEmpty())

0. 常见异常退出条件

  • 参数为空;
  • 表示长度,表示索引的整型为负数,或者超出待索引数组或容器的范围;

1. String 的 startsWith 函数

首先来看 String 类为 startsWith 函数提供的对外接口,有如下形式的俩中函数重载:

public boolean startsWith(String prefix, int toffset);
public boolean startsWith(String prefix) {
    starsWith(prefix, 0);     // 调用的是双参的实现
}

传递进来的参数的含义分别为,prefix:待匹配的字符串,toffset 当前字符串开始比较时的偏移,对于参数应当满足:

  • toffset >= 0;
  • this.value.length >= prefix.length + toffset

也就是:

char[] ta = value;
int pc = prefix.length;

if ((toffset < 0) || (toffset > value.length-pc))
{   // 负数形式的偏移,
    // 偏移加前缀的长度大于此字符串的长度;
    return false;
}

完整源码如下:

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;
    // Note: toffset might be near -1>>>1.
    if ((toffset < 0) || (toffset > value.length - pc)) {
        return false;
    }
    while (--pc >= 0) {
        if (ta[to++] != pa[po++]) {
            return false;
        }
    }
    return true;
}

相关文章:

  • 2021-09-08
  • 2021-07-20
  • 2021-11-07
  • 2021-12-05
  • 2021-12-05
  • 2021-12-05
猜你喜欢
  • 2021-12-05
  • 2022-12-23
  • 2021-12-05
  • 2021-08-22
  • 2021-12-05
  • 2022-03-02
  • 2021-09-30
相关资源
相似解决方案