1

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.

7
  • Check this similar post... stackoverflow.com/questions/28741673/… Commented Apr 8, 2020 at 14:09
  • 1
    Your code handles \ but in your question you claim you want to remove / so which is it? Commented Apr 8, 2020 at 14:11
  • Anyway what is the exact text you are handling and what you want to achieve? If it is some common task maybe using URI/URL classes would be easier? Commented Apr 8, 2020 at 14:13
  • Aside from that you could use regex like convertedUrl = convertedUrl.replaceFirst("^\\\\+", ""); (if you want to remove series of \ at beginning of string). Change \\\\ to / if you want to remove /. Commented Apr 8, 2020 at 14:17
  • Keep in mind that you only need to optimize this for performance if you measure your program's performance and this is the bottleneck Commented Apr 8, 2020 at 14:26

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

Comments

-1

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!

2 Comments

That would replace all / in string. Not what OP wants (at least according to his code).
Also you don't need to escape / in Java regex since it doesn't use /regex/flags syntaks which makes / special, but plain regex where / doesn't have any special meaning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.