Here are some common string operations in Java, along with brief explanations:
1. String Comparison
-
equals(): Compares two strings for content equality.String str1 = "Hello"; String str2 = "Hello"; boolean isEqual = str1.equals(str2); // true -
compareTo(): Compares two strings lexicographically.int result = str1.compareTo(str2); // 0 if equal, negative if str1 < str2, positive if str1 > str2
2. String Replacement
-
replace(oldChar, newChar): Replaces all occurrences of a character.String replaced = str1.replace('l', 'p'); // "Heppo" -
replaceAll(regex, replacement): Replaces all substrings matching a regex pattern.String regexReplaced = "abc123".replaceAll("\\d", "#"); // "abc###"
3. Trimming Whitespace
trim(): Removes leading and trailing whitespace from a string.String trimmed = " Hello ".trim(); // "Hello"
4. Splitting Strings
split(regex): Splits a string into an array based on a regex delimiter.String[] parts = "apple,banana,cherry".split(","); // ["apple", "banana", "cherry"]
5. Finding Substrings
-
indexOf(substring): Returns the index of the first occurrence of a substring.int index = str1.indexOf("l"); // 2 -
lastIndexOf(substring): Returns the index of the last occurrence of a substring.int lastIndex = str1.lastIndexOf("l"); // 3
6. String Conversion
-
toCharArray(): Converts a string to a character array.char[] charArray = str1.toCharArray(); // ['H', 'e', 'l', 'l', 'o'] -
valueOf(): Converts other data types to a string.String numString = String.valueOf(123); // "123"
These operations provide powerful tools for manipulating and processing strings in Java. If you want to practice these operations, consider exploring relevant LabEx labs! Let me know if you have any questions!
