Sunday, April 14, 2024

Java StringBuilder Common Use Cases


Use cases for StringBuilder:

Concatenating Strings

StringBuilder is more efficient than String concatenation using the + operator, especially in loops.


StringBuilder result = new StringBuilder(); for (int i = 0; i < 10; i++)
{
result.append("Number ").append(i).append(", ");
}
// Result: "Number 0, Number 1, Number 2, ..., Number 9, "


Building Dynamic Strings

When constructing strings based on conditions or dynamic values.

StringBuilder message = new StringBuilder("Hello ");
if (user.isLoggedIn())
{
    message.append(user.getUsername()).append("!");
}
else
{
    message.append("Guest!");
}
// Result: "Hello John!" or "Hello Guest!"

 Generating CSV or XML Data

Constructing structured data formats where elements need to be appended in a specific order.

StringBuilder csvData = new StringBuilder(); 
for (Person person : peopleList) 
{         csvData.append(person.getName()).append(",").append(person.getAge()).append("\n"); 
}

Replacing or Removing Substrings

StringBuilder provides methods for replacing or removing specific portions of the content.

StringBuilder text = new StringBuilder("The quick brown fox"); 

text.replace(4, 9, "slow"); // Replace "quick" with "slow" text.delete(10, 15); // Remove "brown" // Result: "The slow fox"

Appending Different Data Types

Appending various types of data without explicitly converting them to strings.

StringBuilder data = new StringBuilder(); 

data.append("Name: ").append(user.getName()).append(", Age: ").append(user.getAge());

Efficient String Manipulation in Loops

When you are concatenating strings inside a loop, StringBuilder can significantly improve performance compared to using String concatenation

StringBuilder result = new StringBuilder(); 

for (int i = 0; i < 1000; i++) 
    result.append("Item ").append(i).append(", ");
}

Building SQL Queries

Constructing dynamic SQL queries.

StringBuilder query = new StringBuilder("SELECT * FROM users WHERE"); 

if (filterByUsername) 
    query.append(" username = '").append(username).append("'"); 
if (filterByAge) 
    query.append(" AND age = ").append(age); 
}

Appending Formatted Strings

When constructing strings with specific formats.

StringBuilder formatted = new StringBuilder();

 formatted.append(String.format("Name: %s, Age: %d", person.getName(), person.getAge()));

Remember, StringBuilder is not thread-safe, so if you need to perform string manipulations in a multi-threaded environment, consider using StringBuffer, which is a thread-safe version of StringBuilder. 

In most cases, StringBuilder is sufficient and provides better performance in a single-threaded context.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...