刷
leetCode
有一个题目需要实现String.indexOf()
的源代码,好奇之下在Intellij IDEA
中查看了它的源代,意外地发现源码中关于在字符串中查找指定字符的下标的优雅代码(至少比我写的优雅),于是乎我打算开个贴记录一下。
String.indexOf(str)
的源代码:
//解释一下:在源码中 indexOf(str) 调用了下面这个重载的方法去实现,
//前三个参数的 source 指的是原字符串的相关参数,
//接下来的三个参数的 target 指的是待查找的目标字符串的相关参数。
//无关代码我则用省略号代替。
static int indexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
//......
char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
//......
}
抽出来的优雅代码则是:
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
我以前的写法是:
if(source[i] != first) {
for(; i <= max; i++) {
if(source[i] == first) {
break;
}
}
}
相比之下,一句 while
代码代替了我专门开了个 for
循环+ if
+ break
所实现的功能(已写单元测试测试过两段代码的功能,是一样的)。
个人觉得源代码还是优雅一点,开个贴记录一下。