String Processing Techniques
String Parsing and Manipulation
Splitting Strings
The split()
method allows dividing strings into arrays:
String data = "Java,Python,C++,JavaScript";
String[] languages = data.split(",");
// Result: ["Java", "Python", "C++", "JavaScript"]
Joining Strings
Use String.join()
for combining array elements:
String[] words = {"LabEx", "Java", "Tutorial"};
String result = String.join(" ", words);
// Result: "LabEx Java Tutorial"
Advanced String Processing Techniques
Regular Expression Processing
String input = "Contact: +1-555-123-4567";
String phoneNumber = input.replaceAll("[^0-9]", "");
// Result: "15551234567"
String Tokenization
graph LR
A[Input String] --> B[Tokenizer]
B --> C[Token 1]
B --> D[Token 2]
B --> E[Token 3]
StringTokenizer tokenizer = new StringTokenizer("Hello World Java", " ");
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
Method |
Description |
Example |
trim() |
Removes whitespace |
" Java ".trim() // "Java" |
replace() |
Replaces characters |
"Java".replace('a', 'X') // "JXvX" |
replaceAll() |
Replaces using regex |
"Java123".replaceAll("\\d", "*") // "Java***" |
Complex String Manipulation
StringBuilder for Efficient Processing
StringBuilder builder = new StringBuilder();
builder.append("LabEx ")
.append("Java ")
.append("Tutorial");
String result = builder.toString();
// Result: "LabEx Java Tutorial"
Pattern Matching
import java.util.regex.Pattern;
import java.util.regex.Matcher;
String text = "Email: [email protected]";
Pattern pattern = Pattern.compile("\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("Valid email: " + matcher.group());
}
- Use
StringBuilder
for multiple string modifications
- Prefer
replaceAll()
for complex replacements
- Cache compiled regex patterns
- Minimize string object creation
Error Handling in String Processing
try {
String number = "123abc";
int value = Integer.parseInt(number);
} catch (NumberFormatException e) {
System.out.println("Invalid number format");
}
By mastering these string processing techniques, developers can efficiently manipulate text data in Java applications, leveraging LabEx's comprehensive learning resources to enhance their programming skills.