About Lesson
A string is a sequence of characters. Strings in Java are represented by the String
class, which is part of the Java standard library. Here are some common string manipulation functions in Java:
length()
: Returns the length of the string.charAt(int index)
: Returns the character at the specified index in the string.substring(int beginIndex, int endIndex)
: Returns a new string that is a substring of the original string, starting atbeginIndex
and ending atendIndex
(exclusive).concat(String str)
: Concatenates the specified string to the end of the original string.indexOf(String str)
: Returns the index of the first occurrence of the specified string within the original string, or -1 if the specified string is not found.replace(char oldChar, char newChar)
: Returns a new string where all occurrences of theoldChar
character are replaced with thenewChar
character.
Here’s an example of how to use these functions:
String str = "Hello, world!";
int length = str.length(); // length is 13
char firstChar = str.charAt(0); // firstChar is 'H'
String substr = str.substring(7, 12); // substr is "world"
String newStr = str.concat(" Goodbye!"); // newStr is "Hello, world! Goodbye!"
int index = str.indexOf("world"); // index is 7
String replacedStr = str.replace('o', 'a'); // replacedStr is "Hella, warld!"
I hope that helps! Let me know if you have any further questions.
Join the conversation