gpt4 book ai didi

java - 查找 url 路径最后一部分的最快方法是什么?

转载 作者:行者123 更新时间:2023-12-02 04:01:41 24 4
gpt4 key购买 nike

我有一个网址,例如:

“http://www.someco.com/news/2016-01-03/waterloo-station”

该网址从不包含查询字符串。

提取字符串“waterloo-station”的最简洁方法是什么?

当然我可以使用以下代码:

url.substring(url.lastIndexOf('/') + 1))

但我对它并不完全满意,因为它必须执行最后一个索引的搜索,然后获取子字符串。我想知道是否有更好的方法(使用正则表达式?)在一步中获得相同的结果。

当然,当执行数十亿次时,解决方案应该会明显更快。

最佳答案

我不认为它可以改进。简而言之,因为搜索最后一个索引是一个简单的操作,所以可以使用快速算法来实现(直接在 String 类中!),而正则表达式很难达到如此快的速度。正如您所看到的,第二次访问字符串的成本非常低:它只是新字符串的初始化。

如果有一个直接在 String 类中实现的专用方法,速度可能会更快。

如果想了解更多细节,可以自行查看JDK中的代码。为了您的方便,复制到这里。

下面的代码是我的JDK中lastIndexOf()方法的实现:

public int lastIndexOf(int ch, int fromIndex) {
int min = offset;
char v[] = value;

int i = offset + ((fromIndex >= count) ? count - 1 : fromIndex);

if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
for (; i >= min ; i--) {
if (v[i] == ch) {
return i - offset;
}
}
return -1;
}

int max = offset + count;
if (ch <= Character.MAX_CODE_POINT) {
// handle supplementary characters here
char[] surrogates = Character.toChars(ch);
for (; i >= min; i--) {
if (v[i] == surrogates[0]) {
if (i + 1 == max) {
break;
}
if (v[i+1] == surrogates[1]) {
return i - offset;
}
}
}
}
return -1;
}

直接在 String 类中实现,它可以访问其私有(private)成员:

/** 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;

它不适用于子字符串。同时,substring 方法在 Java 中非常快,因为它不会创建新的 char 数组,而只是创建一个新的 String 对象并更改偏移量和计数:

public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}

// Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}

关于java - 查找 url 路径最后一部分的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34829065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com