Explain Codes LogoExplain Codes Logo

Java - removing first character of a string

java
string-manipulation
unicode
performance
Alex KataevbyAlex Kataev·Aug 16, 2024
TLDR

Sail in the sea of code and cast off the "first mate" character from your String ship with the substring(1) command:

String voyage = "Example".substring(1); // Leaves you with "xample"

Ahoy!: Make sure your string isn't a deserted island (aka, empty) to avoid walking the plank into a sea of exceptions.

Battling against the ghostly empty strings

Fight off the phantom empty strings before you execute substring(1). Ghostly strings can scare your code into exceptions:

if (!str.isEmpty()) { str = str.substring(1); // "Ghost busted!" - Venkman, probably. }

Sneaky conditional removals

Sometimes, you want to leave behind the first character only if it's as unwanted as a mutiny. Set a lookout with startsWith and use the ternary operator to decide its fate:

str = str.startsWith("#") ? str.substring(1) : str; // The ternary operator - quick as a pirate's cutlass.

Targeting the first 'X marks the spot'

To vanish the first occurrence of a particular character, trust the old map replaceFirst:

str = str.replaceFirst("a", ""); // Wait, we've got too many 'a's. That one's gotta walk the plank.

The all-seeing 'replace'

To make all instances of a character walk the plank, summon the all-powerful replace:

str = str.replace("a", ""); // 'a's? In this economy? Out you go.

Advanced techniques for seasoned sailors

Smooth sailing with StringBuilder

Navigate mutable strings, by using StringBuilder as your trusty compass:

StringBuilder reliableCompass = new StringBuilder("Example"); reliableCompass.deleteCharAt(0); // "xample", lost an 'E' there, but the compass always points to 'x'am!

Mastering the unpredictable seas of Unicode

Sail the choppy waters of Unicode and special characters with the right map to handle surrogate pairs:

String newLands = "😊Example"; newLands = newLands.offsetByCodePoints(0, 1).substring(1); // Unicode - Makes total sense if you don't think about it.

Rapidly performing operations in a maelstrom-like loop? Lower the anchor and consider your strategy for riding the storm:

for (int i = 0; i < bigListOfAdventures.size(); i++) { bigListOfAdventures.set(i, bigListOfAdventures.get(i).substring(1)); // That's one way to get rid of excess baggage! }