Java String Manipulation: 5 Key Recipes for Technical Interviews (Part 1)
Overview
String manipulation is an essential skill in programming, virtually unavoidable in technical interviews and coding challenges.
In this article, I will share valuable Java 17 String Recipes gleaned from a decade of coding experience.
Before We Start
Disclosure: This post contains affiliate links. If you purchase through these links, I may earn a small commission at no additional cost to you. As an Amazon Associate, I earn from qualifying purchases.
Do you want to ace your next technical interview? Check out Cracking the Coding Interview, a comprehensive guide to help you prepare for technical interviews and Coding Challenges. The book takes you through the classic recruitment process and gives you tips for each stage. The interview process of major companies such as Google, Microsoft, Amazon, Apple and Facebook is presented. Over 700 technical interview questions are presented. The author guides you through the process of solving each question, providing clues to help you find the solution on your own. The final solution to each problem is presented at the end, along with the corresponding Java code.
Now let's get back to our tutorial!
Version check
This tutorial has been tested with the following tools :
- Java 17
- Junit 5.9.2
String Recipes 1: Remove Whitespace
How would you remove trailing and leading whitespace from a string?
Assuming that you have the following string literal : " Hello World "
How would you make it "Hello World" ?
String.trim()
Use The String.trim() method deletes blank characters at the beginning and end of a string. Note that this method only considers ASCII characters.
@Test
void testReplaceWhiteSpaceWithTrim(){
//Given
String toClear = " Hello World ";
//When
String result = toClear.trim();
//Then
assertEquals("Hello World", result);
}
String.strip()
Use Java 11 The String.strip() method is an evolved version of String.strim() that takes UNICODE characters into account. It should be noted that this method was not introduced until Java 11.
@Test
void testReplaceWhiteSpaceWithStrip(){
//Given
char unicodeSpaceCharacter = '\u2003';
String toClearWithUnicode = unicodeSpaceCharacter +"Hello World" + unicodeSpaceCharacter;
//When
String result = toClearWithUnicode.strip();
//Then
assertEquals("Hello World", result);
}
String Recipes 2: Check if a String is Empty or Blank
It's important to note the difference between these two terms. A string is considered "Empty" when it is of size 0. On the other hand, it's considered "Blank" when it's made up entirely of "white" characters.
isEmpty
@Test
void testIsEmpty(){
//Given
char asciiSpaceCharacter = ' ';
char unicodeSpaceCharacter = '\u2003';
String asciiBlankString = asciiSpaceCharacter + "";
String unicodeBlankString = unicodeSpaceCharacter+"";
String emptyString = "";
//When
//Then
assertFalse(unicodeBlankString.isEmpty());
assertFalse(asciiBlankString.isEmpty());
assertTrue(emptyString.isEmpty());
assertTrue(asciiBlankString.trim().isEmpty());
assertTrue(unicodeBlankString.strip().isEmpty());
}
isBlank
@Test
void testIsBlank(){
//Given
char asciiSpaceCharacter = ' ';
char unicodeSpaceCharacter = '\u2003';
String asciiBlankString = asciiSpaceCharacter + "";
String unicodeBlankString = unicodeSpaceCharacter+"";
//When
//Then
assertTrue(unicodeBlankString.isBlank());
assertTrue(asciiBlankString.isBlank());
}
String Recipes 3: Compare two Strings
In Java, there are two ways of comparing two strings (and objects in general). The first is to use the "==" symbol and the second is to use the equals()
method.
Using the double equal symbol "=="
When using this approach, we are actually comparing the references of the two strings.
You should use this if and only if you are working with string created without the new keyword.
@Test
void testStringCompareUsingDoubleEqualSymbol(){
//Given
String string1 = "String1";
String string2 = "String1";
String string3 = new String("String1");
//When
//Then
assertTrue(string1 == string2);
assertFalse(string1 == string3);
}
String.equals()
(Recommended)
Using This is the right way of comparing two strings, as it will compare the content of the strings, not their references.
@Test
void testStringCompareEqual(){
//Given
String string1 = "String1";
String string2 = "String1";
String string3 = new String("String1");
//When
//Then
assertTrue(string1.equals(string2));
assertTrue(string1.equals(string3));
}
Best Practice : Always code defensively : prefer this "myString".equals(myOtherString)
over this myOtherString.equals("myString")
to prevent unexpected NullPointerException.
String Recipes 4: Find and Replace
String.matches()
How to use This method takes a regular expression as a parameter and returns true
if it is found in the string and false
otherwise.
It can be very useful for searching for a sub-string in a string.
@Test
void testStringMatches(){
//Given
String myString = "Hello World";
//When
boolean containsLetterL = myString.matches(".*[l].*");
boolean containsDigit = myString.matches("\\d");
//Then
assertTrue(containsLetterL);
assertFalse(containsDigit);
}
String.replace()
and String.replaceAll()
Understand the difference between You need to know that both methods do exactly the same thing. The only difference is that String.replace()
accepts a string as a parameter, whereas String.replaceAll()
accepts a regular expression as a parameter.
@Test
void testStringReplaceAndReplaceAll(){
//Given
String myString = "Hello World";
//When
String updatedWithReplace = myString.replace("l","L");
String updatedWithReplaceAll = myString.replaceAll("[l]","L");
//Then
assertEquals("HeLLo WorLd",updatedWithReplace);
assertEquals("HeLLo WorLd",updatedWithReplaceAll);
}
Best Practice: Avoid using String.replaceAll()
when you are not dealing with regular expressions. Doing so will result in a huge performance impact.
String Recipes 5: Tokenize a String
Tokenization is the process of breaking up a string into so-called tokens. Oftentimes, these tokens are words, numbers, and/or punctuation.
There are different ways of tokenizing a string in Java. We will be focusing on what is for me the easiest way : String.split()
String.split()
will take the delimiter as a Regex and return the tokens into an array of strings.
@Test
void testStringTokenizing(){
//Given
String myString = "Hello, World, From, Paris";
//When
String[] tokens = myString.split(",");
//Then
assertEquals(4,tokens.length);
assertEquals("Hello",tokens[0].trim());
assertEquals("World",tokens[1].trim());
assertEquals("From",tokens[2].trim());
assertEquals("Paris",tokens[3].trim());
}
Tip: Since String.split() accepts a regex, you can use String.split("\\s")
on a sentence to obtain the list of words.
Conclusion
In this article, we looked at some important techniques for manipulating strings in Java.
These recipes will be very useful for your coding challenges. In our next article in the series, we'll cover other recipes for string manipulation in Java.
Did you find this blog post useful? Feel free to drop a thumbs up or comment. If you've had any difficulty completing this tutorial, leave me a comment, and I'll be happy to help.
The complete code used in this article can be found here in GitHub
Happy Coding! And good luck with your next coding challenge!
Mastering Java string manipulation is crucial for technical interviews. Key recipes include reversing a string using StringBuilder’s reverse() method and checking for palindromes by sanitizing and comparing the string to its reverse. Additionally, converting a string to a character array with toCharArray(), finding substrings using indexOf() and substring(), and splitting a string with the split() method are essential skills. These techniques enhance your coding abilities, whether tackling interview questions or managing tasks in Stardew Valley.
https://stardewvalley-apk.com/
Working on some Java string manipulation for my new project while enjoying a movie on <a href=“https://thefreecine.com/”>Freecine</a>. The combination of coding and great entertainment is unbeatable!
Learn advanced Java string manipulation techniques with exclusive tutorials on our streaming app. Master powerful methods to manipulate strings efficiently and unlock new possibilities in your programming projects. From basic operations to complex algorithms, our expert-led content will help you sharpen your skills and become a proficient Java developer. Dive into the world of string manipulation today and level up your coding expertise with our streaming app.
https://redboxtvs.org/