In Java, there are several useful string methods that you can use to manipulate and work with strings. Here are some commonly used string methods:
-
length(): Returns the length of the string.
String str = "Hello"; int length = str.length(); // 5 -
charAt(int index): Returns the character at the specified index.
char ch = str.charAt(1); // 'e' -
substring(int beginIndex, int endIndex): Returns a substring from the specified begin index to the end index (exclusive).
String sub = str.substring(1, 4); // "ell" -
indexOf(String str): Returns the index of the first occurrence of the specified substring.
int index = str.indexOf("l"); // 2 -
toLowerCase(): Converts all characters in the string to lowercase.
String lower = str.toLowerCase(); // "hello" -
toUpperCase(): Converts all characters in the string to uppercase.
String upper = str.toUpperCase(); // "HELLO" -
trim(): Removes leading and trailing whitespace from the string.
String trimmed = " Hello ".trim(); // "Hello" -
replace(char oldChar, char newChar): Replaces all occurrences of a specified character with a new character.
String replaced = str.replace('l', 'p'); // "Heppo" -
split(String regex): Splits the string into an array of substrings based on the specified regular expression.
String[] parts = str.split("l"); // ["He", "lo"] -
equals(Object anObject): Compares the string to the specified object for equality.
boolean isEqual = str.equals("Hello"); // true
These methods provide a variety of functionalities to handle strings effectively in Java.
