在Java 8或更新版本中实现while循环的最佳方法是:

huangapple go评论58阅读模式
英文:

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!

huangapple
  • 本文由 发表于 2020年4月8日 22:08:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/61102714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定