1

I am trying to convert Java String into HTML readable code.
For Example: H e l l o W o r l d as &#x48 &#x65 &#x6c &#x6c &#x6f &#x57 &#x6f &#x72 &#x6c &#x64

What I did so far:

    private static String convertToAscii(String str) {
        for(int i=0; i<str.length(); i++) {
            str += "&#"+(int)str.charAt(i);
        }
    return str;
    }

its taking too much time plus processor fan making noice.

Thanks in advance

2 Answers 2

1

This gif is not a perfect representation of what's happening here, but it gets the basic ideaenter image description here

Over here...

for(int i=0; i<str.length(); i++)

...You are looping through the String named str.

But here...

str += ...

...You are adding to str.

You are trying to get to the end of str, but you are literally adding to str for each loop. You have created an infinite loop.

Add to a different String. Like this.


   private static String convertToAscii(String str) {
   
      String output = "";
   
      for(int i=0; i<str.length(); i++) {
         output += "&#"+(int)str.charAt(i);
      }
         
      return output;
   
   }
   
Sign up to request clarification or add additional context in comments.

2 Comments

And in case you don't get the joke, once Gromit's box runs out of train tracks to put down, he will get a StackOverflow error, just like you.
@davidalayachew: he'd get an OutOfMemoryError (OutOfTrainTracksError?), since there's no recursion happening here.
1

You can also do something like that:

private static String convertToAscii(String str) { 
    return str     
              .chars() 
              .boxed()
              .reduce("", (subRes, currVal) -> subRes + "&#" + currVal + ";" , (subVal, mappedVal) -> subVal + "" + mappedVal);

Its quicker with Java >= 8

Comments

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.