Both String and StringBuilder are backed by arrays and charAt() gets the value at the specified index.
Since String is immutable, it must make a defensive copy before returning the array. So it has some additional overhead. But imo, this would only be a problem for very large strings or repeated conversion of many strings to arrays. It all depends how how you are using it.
How is String charAt implemented in Java?
Appending character at the front in the StringBuilder
just do a .reverse on the sb.toString() at the end.. surely that's 10x more readable
More on reddit.comHow to set a character of a String?
Replacing a single specific character in a string. - Processing Forum
Videos
If I'm not mistaken, StringBuilder objects are stored as a char array. So when we use the String charAt method, does Java convert the string into a char array as well?
I have this piece of code
StringBuilder sb = new StringBuilder(); if(strX.charAt(i-1)==strY.charAt(j-1)){ sb.insert(0,strX.charAt(i-1)); }
I get error on the HackerRank that terminated due to timeout. If I remove this piece of code, everything else works fine.
I was wondering if
-
this is the optimized way to keep on appending characters at the front?
-
Does this approach work?
just do a .reverse on the sb.toString() at the end.. surely that's 10x more readable
-
Inserting at index 0 has a time complexity of O(n). So if you already have 500 characters in the internal array, it needs to shift those 500 chars over just to make space for the new char at the first index. So no, it is not.
-
Yes, it works.
Do what OffbeatDrizzle suggests, or simply create a function that will iterate over the StringBuilder in reverse and print out the contents- assuming this is what is required. If you need an object then reversing it at the end is the best way.