Advertisement
Google Ad Slot: content-top
Java String Methods
Method |
Description |
Example |
|---|---|---|
charAt(int index) |
Returns the character at the specified index. |
"Hello".charAt(1) // 'e' |
length() |
Returns the length of the string. |
"Java".length() // 4 |
substring(int start, int end) |
Extracts a substring. |
"Hello".substring(0, 4) // Hell |
indexOf(String str) |
Returns the first index of a substring. |
"Hello".indexOf("l") // 2
|
lastIndexOf(String str) |
Returns the last index of a substring. |
"Hello".lastIndexOf("l") // 3
|
replace(char old, char new) |
Replaces characters in the string. |
"Java".replace('a', 'o') // Jovo
|
toUpperCase() |
Converts the string to uppercase. |
"java".toUpperCase() // JAVA |
toLowerCase() |
Converts the string to lowercase. |
"JAVA".toLowerCase() // java |
trim() |
Removes leading and trailing spaces. |
" Java ".trim() // Java |
split(String regex) |
Splits the string into an array based on a regex. |
"a,b,c".split(",") // ["a", "b", "c"]
|
startsWith(String prefix) |
Checks if the string starts with the prefix. |
"Hello".startsWith("He") // true
|
endsWith(String suffix) |
Checks if the string ends with the suffix. |
"Hello".endsWith("lo") // true
|