【软构随记】一个较复杂的spec分析——regionMatches()

课程讲义上的一道思考题。

首先来看spec的具体内容:

Tests if two string regions are equal. A substring of this String object is compared to a substring of the argument other. The result is true if these substrings represent character sequences that are the same, ignoring case if and only if ignoreCase is true. The substring of this String object to be compared begins at index toffset and has length len. The substring of other to be compared begins at index ooffset and has length len. The result is false if and only if at least one of the following is true: toffset is negative. ooffset is negative. toffset+len is greater than the length of this String object. ooffset+len is greater than the length of the other argument. ignoreCase is false and there is some nonnegative integer k less than len such that: this.charAt(toffset+k) != other.charAt(ooffset+k) ignoreCase is true and there is some nonnegative integer k less than len such that: Character.toLowerCase(this.charAt(toffset+k)) != Character.toLowerCase(other.charAt(ooffset+k)) and: Character.toUpperCase(this.charAt(toffset+k)) != Character.toUpperCase(other.charAt(ooffset+k)) Params: ignoreCase – if true, ignore case when comparing characters. toffset – the starting offset of the subregion in this string. other – the string argument. ooffset – the starting offset of the subregion in the string argument. len – the number of characters to compare. Returns: true if the specified subregion of this string matches the specified subregion of the string argument; false otherwise. Whether the matching is exact or case insensitive depends on the ignoreCase argument

这个方法的作用是比较两个String的指定位置开始的指定长度的子串是否相同,其接受五个参数:

  • ignoreCase:布尔型,为true是比较字符串忽略大小写

  • toffset:int型,当前字符串开始比较的位置

  • other:参与比较的另一个字符串

  • ooffset:other中开始比较的位置

  • len:要比较的子串的长度

其@param和@returns部分没有什么特别之处,最值得借鉴的是其前面对具体返回情况的描述部分。首先写明了比较的方法和各个参数的作用,之后详细写明了几种返回false的情况:

  • toffset或ooffset中有负数

  • toffset或ooffset+len后超出了对应字符串的长度

  • 在ignoreCase为false时存在小于len的非负整数k使得this.charAt(toffset+k) != other.charAt(ooffset+k)(存在两个字符不等)

  • 在ignoreCase为true时存在小于len的非负整数k使得

  • Character.toLowerCase(this.charAt(toffset+k)) != Character.toLowerCase(other.charAt(ooffset+k)) 且 Character.toUpperCase(this.charAt(toffset+k)) != Character.toUpperCase(other.charAt(ooffset+k))

一点题外话:这里的最后一个要求看起来有些冗余,查看代码注释发现这样做的原因是对于Georgian alphabet(如 ქართული დამწერლობა)大小写转换规则比较复杂,toUppercase的返回不一定准确。

总之,这个spec的内容比我们平时自己实现的函数要复杂,但作者描述返回值时的条理性与严谨性值得我们学习。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值