java string method with example

 Here are some examples of Java string methods with explanations:

length():


String myString = "Hello, world!";
int length = myString.length();
System.out.println(length);  // Output: 13

The length() method returns the number of characters in the string.

toLowerCase():


String myString = "HeLLo, WORld!";
String lowerCaseString = myString.toLowerCase();
System.out.println(lowerCaseString);  // Output: "hello, world!"

The toUpperCase() method converts all lowercase characters in a string to uppercase characters.

trim():

String myString = "   Hello, world!   ";
String trimmedString = myString.trim();
System.out.println(trimmedString);  // Output: "Hello, world!"

The trim() method removes any whitespace characters from the beginning and end of a string.

split():

String myString = "Hello, world!";
String[] parts = myString.split(",");
System.out.println(Arrays.toString(parts));  // Output: ["Hello", " world!"]

The split() method splits a string into an array of substrings based on a specified delimiter (in this case, the comma).

join():


String[] myArray = {"apple", "banana", "cherry"};
String joinedString = String.join(", ", myArray);
System.out.println(joinedString);  // Output: "apple, banana, cherry"

replace():

String myString = "Hello, world!";
String replacedString = myString.replace("o", "x");
System.out.println(replacedString);  // Output: "Hellx, wxrld!"

The replace() method replaces all occurrences of a specified substring in a string with another substring (in this case, all "o" characters with "x").

substring():

String myString = "Hello, world!";
String substring1 = myString.substring(7);  // "world!"
String substring2 = myString.substring(0, 5);  // "Hello"
System.out.println(substring1);
System.out.println(substring2);

The substring() method is used to extract a portion of a string. The first parameter specifies the starting index of the substring (inclusive), and the second parameter (optional) specifies the ending index of the substring (exclusive). In the example above, substring1 is a substring that starts at index 7 (the "w" in "world") and goes to the end of the string, while substring2 is a substring that starts at index 0 (the "H" in "Hello") and goes up to index 5 (the "," in "Hello, world!").

charAt(int index): 

Returns the character at the specified index in the string.

String str = "Hello, World!";
char ch = str.charAt(4); // ch = 'o'
indexOf(char ch):

Returns the index of the first occurrence of the specified character in the string.


String str = "Hello, World!";
int index = str.indexOf('o'); // index = 4

Post a Comment

0 Comments