英文:
Best way to implement while loop in java 8 or later
问题
我必须从字符串开头删除所有的斜杠(/)。所以我已经写了以下代码:
while (convertedUrl.startsWith("\\"))
{
convertedUrl = convertedUrl.substring(1);
}
上述代码为每个子字符串创建了一个字符串。在Java 8或更高版本中,有没有更好的方法来编写这段代码?在考虑内存利用和性能的情况下,我该如何做呢?
英文:
I have to remove all slash (/) from the beginning of string.
So I have written
while (convertedUrl.startsWith("\\"))
{
convertedUrl = convertedUrl.substring(1);
}
Above code creates string for each substring.
Is there any better way to write this code in java 8 or later?
How can I do it keeping mind memory utilisation and performance.
答案1
得分: 4
我会猜测:
int len = str.length();
int i=0;
for (; i<len && str.charAt(i) == ''\\'; ++i) {
;
}
return str.substring(i);
我写 str
而不是 convertedUrl
因为这应该在自己的方法中。
虽然这不太可能成为性能瓶颈,但原始代码的运行速度可能会像 O(n^2) 一样慢(取决于实现方式)。
英文:
I would guess at:
int len = str.length();
int i=0;
for (; i<len && str.charAt(i) == '\\'; ++i) {
;
}
return str.substring(i);
I write str
instead of convertedUrl
because this should be in its own method.
It is unlikely this is a performance bottleneck, but the original code may run as slow as O(n^2) (depending on implementation).
答案2
得分: -1
可以简单地使用类似这样的方式,一次性替换所有的“/”:
convertedUrl = convertedUrl.replaceAll("/", "");
对于最初的方法,我很抱歉,但我认为这将起到作用:
convertedUrl = convertedUrl.replaceFirst("^/", "");
或者这个:
convertedUrl = convertedUrl.replaceAll("^/", "");
这两种方法都能完成任务!因为它们都替换了所有前导的“/”字符。
英文:
can you simply not use something like this, to replace all the "/" in one go
convertedUrl = convertedUrl.replaceAll("\\/","");
I am sorry for the initial one, but I think this will do:
convertedUrl = convertedUrl.replaceFirst("^/*","");
OR this:
convertedUrl = convertedUrl.replaceAll("^/*","");
both will get the job done!
as they replaces all the leading "/" chars!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论