A Review of String and StringBuilder in Java
What is String??
String is a special Object class that is implemented by Java. Unlike other data structures like arrayList, HashMap…etc, you do not need to import String from java.utils, because String is specifically implemented inside the java.lang package. If you look at the source code, you will see that in Java 11, inside the String class, there is a public final byte[] as a field.
public final class String implements java.io.Serializable, Comparable<String>, CharSequence
private final byte[] value[];
This leads to some unique properties that String has.
- String is immutable, immutable means you cannot change characters internally, for example: “abc” + “d” -> will lead to open a new memory space for a new String
- Can lead to index out of bound exception, if you access index over its length
- Can lead to null pointer exception, if you access a method in a null object.
How to create a String Object in Java
- Directly define method:
String a = "abc"
- new String keyword:
String a = new String("aaa")
- intern() method:
String s2 = a.intern()
What API do we need to know about String?
The following table is a quick guide that include all APIs you should know about when you use Java for coding interviews. You can find the details of String APIs here.
String API | Comment or things need to be aware of |
---|---|
char charAt(int index) | |
int compareTo(String s2) | This API compare String based on their lexicographically order, \Capital character is greater than non-capital character. \ ABC.compareTo(abc) would return -1, meaning ABC is smaller than abc |
int compareToIgnoreCase(String s2) | same API as above just without cases |
String concat(String s2) | same as adding String “+” |
boolean equals(String s2) | |
boolean equalsIgnoreCase(String s2) | |
replace(char oldChar, char newChar) | non-static method |
replace(CharSequence oldS, CharSequence newS) | non-static method |
int indexOf(char c) | |
int indexOf(String s1) | |
int length() | |
String substring(int beginIndex) | |
String substring(int beginIndex, int length) | |
char[] toCharArray() | |
String toLowerCase() | |
String toUpperCase() | |
String trim() | |
String repeat(int repeatTime) | it concat the same String for repeatTime times |
What is StringBuilder()?
StringBuilder is a class that Java implemented to allow user to “dynamically modify” the String. Again, StringBuilder is in Java.lang package, so you can use it without importing it.
How to create StringBuilder in Java?
Just like creating an Object: StringBuilder sb = new StringBuilder()
What API do we need to know about StringBuilder?
StringBuilder API | Comment or things need to be aware of |
---|---|
append(char ch) | |
append(char[] charArray) | |
append(char[] charArray, int startIndex, int length) | |
append(CharSequence s) | if append null, it will append “null” inside sb |
append(CharSequence s, int start, int length) | |
append(String s) | |
int capacity() | Yes just like an ArrayList, StringBuilder has capacity |
char charAt(int index) | if it exceeds length, it can throw exception |
delete(int startIndex, int length) | |
deleteCharAt(int index) | |
int indexOf(String str) | |
int indexOf(String str, int fromIndex) | |
insert(int index, String s) | it put the String into the StringBuilder, and push the rest of the String back |
int lastIndexOf(String) | lastIndexOf return the first index of the rightmost occurrence. |
replace(int startIndex, int length, String str) | |
reverse() | |
setCharAt(int index, char ch) | |
setLength(int newLength) | Be aware of the exact length, if set too much length, it will appear a lot of empty useless charcode |
subString(int startIndex) | |
substring(int startIndex, int length) | |
toString() |
String Processing Interviewing Questions
As the old saying: when you see a question that is String Processing type of question, you will know it is a String Processing type of question. One good thing about String Processing type of question is that it is very easy to identify. Usually this type of algorithmic question is not hard in Logic, but ,most of the time, the question itself is very annoying to cover all cases, and the code can get very long and reluctant as well. If the question itself is asking to implement the above mentioned String APIs, you probably will not able to implement it using StringBuilder(the interviewer will ask you to do it in-place). Here is the summary of this type of question.
- ask for clairification first, which character can be in the input String, which characters dont, this is very important, can save you a lot of times from nasty edge cases.
- if the problem itself involve integers, ask for signs character.
- Discuss different synario case by case, list them out visually.
- most of the time, it will utilize two-pointer techniques. left side of slow pointer is what i want to keep for the result, while fast pointer is used to traverse the rest of the String.
Practice Question by topics
String Removal:
Problem Number | Problem | Solution |
---|---|---|
1 | remove certain character from String | Solution |
2 | Remove Spaces | Solution |
3 | Remove All Adjacent Duplicates In String | Solution |
4 | Remove All Adjacent Duplicates in String II | Solution |
5 | Remove Comments | Solution |
6 | Remove All Occurrences of a Substring | Solution |
7 | Removing Stars From a String | Solution |
String Reversal:
Problem Number | Problem | Solution |
---|---|---|
1 | Reverse String | |
2 | Reverse String II | |
3 | Reverse Vowels of a String | |
4 | Reverse Words in a String |
String Palindrome Series:
Problem Number | Problem | Solution |
---|---|---|
1 | Valid Palindrome | |
2 | Valid Palindrome II | |
3 | Valid Parentheses |
String to Integer, Integer to String Series:
Problem Number | Problem | Solution |
---|---|---|
1 | Integer to Roman | |
2 | Roman to Integer | |
3 | Excel Sheet Column Title | |
4 | Excel Sheet Column Number | |
5 | Cells in a Range on an Excel Sheet | |
6 | String to Integer (atoi) |
String to Math Operation:
Problem Number | Problem | Solution |
---|---|---|
1 | Add Binary | |
2 | Add String | |
3 | Add String with negative input | |
4 | Multiply String |
String Replace, Modify String Series:
Problem Number | Problem | Solution |
---|---|---|
1 | Find the Index of the First Occurrence in a String | |
2 | Rearrange Spaces Between Words | |
3 | String Replace | |
4 | Compress String | |
5 | Decompress String I | |
6 | Decompress String II | |
7 | Text Justification |
Split String