String Manipulation Techniques
Basic String Operations
Conversion Methods
// Convert to uppercase and lowercase
String text = "LabEx Programming";
String upperCase = text.toUpperCase(); // "LABEX PROGRAMMING"
String lowerCase = text.toLowerCase(); // "labex programming"
// Trim whitespace
String paddedText = " LabEx ";
String trimmedText = paddedText.trim(); // "LabEx"
String Searching and Checking
Finding Substrings and Characters
String sample = "Welcome to LabEx Programming";
// Check if string contains substring
boolean contains = sample.contains("LabEx"); // true
// Find index of substring
int index = sample.indexOf("LabEx"); // returns starting index
int lastIndex = sample.lastIndexOf("a"); // returns last occurrence
String Replacement Techniques
String original = "Hello World, Hello Java";
// Replace specific characters
String replaced = original.replace("Hello", "Hi");
// Result: "Hi World, Hi Java"
// Replace using regex
String regexReplaced = original.replaceAll("\\s", "_");
// Result: "Hello_World,_Hello_Java"
String Splitting and Joining
// Splitting strings
String csv = "LabEx,Programming,Java";
String[] parts = csv.split(",");
// parts = ["LabEx", "Programming", "Java"]
// Joining arrays
String[] words = {"LabEx", "is", "awesome"};
String joined = String.join(" ", words);
// Result: "LabEx is awesome"
Advanced String Manipulation
String Builder for Efficient Modifications
StringBuilder builder = new StringBuilder("LabEx");
builder.append(" Programming")
.insert(0, "Learn ")
.replace(0, 5, "Study");
// Result: "Study LabEx Programming"
String Comparison Techniques
graph TD
A[String Comparison] --> B[equals()]
A --> C[equalsIgnoreCase()]
A --> D[compareTo()]
Comparison Methods
String s1 = "hello";
String s2 = "HELLO";
// Case-sensitive comparison
boolean exactMatch = s1.equals(s2); // false
// Case-insensitive comparison
boolean caseInsensitiveMatch = s1.equalsIgnoreCase(s2); // true
// Lexicographic comparison
int comparisonResult = s1.compareTo(s2); // negative value
Regular Expression Techniques
// Validate email format
String email = "[email protected]";
boolean isValidEmail = email.matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
// Formatted string creation
String formatted = String.format("Name: %s, Age: %d", "LabEx User", 25);
// Result: "Name: LabEx User, Age: 25"
Common String Manipulation Patterns
Operation |
Method |
Example |
Length |
length() |
"LabEx".length() == 5 |
Substring |
substring() |
"LabEx".substring(0,3) == "Lab" |
Starts/Ends With |
startsWith(), endsWith() |
"LabEx".startsWith("Lab") == true |