# Use Offset Based String Methods
# Description
This rule avoids creating intermediate String
instances by making use of the overloaded offset based methods in the String API. For example, if substring(beginIndex)
(opens new window) is followed by startsWith(aString)
(opens new window), then both invocations are removed and startsWith(aString, beginIndex)
(opens new window) is used instead.
# Benefits
Reduces the number of String objects whose sole purpose is to indicate an offset.
# Tags
# Code Changes
# Using String startsWith
Pre
String str = "Hello World!";
boolean startsWith = str.substring(6).startsWith("World");
Post
String str = "Hello World!";
boolean startsWith = str.startsWith("World", 6);
# Using String indexOf
Pre
String str = "Hello World!";
int index = str.substring(6).indexOf("d");
Post
String str = "Hello World!";
int index = Math.max(str.indexOf("d", 6) - 6, -1);
# Using String lastIndexOf
Pre
String str = "Hello World!";
int index = str.substring(6).lastIndexOf("d");
Post
String str = "Hello World!";
int index = Math.max(str.lastIndexOf("d", 6) - 6, -1);
Use a Java Refactoring Tool
Automate this Refactoring system-wide
You can apply this refactoring for free with the jSparrow Eclipse IDE plug-in.
Install the plug-in for Eclipse IDE: Eclipse Marketplace.