Java - String Functions

Strings are a commonly used data type in Java programming. They represent a sequence of characters, and Java provides several built-in functions for manipulating them. Here are ten commonly used string functions:

length(): This function returns the length of a string in terms of the number of characters.

String str = "Hello World";
int len = str.length();
System.out.println("Length of the string is " + len); //Output : Length of the string is 11

charAt(): This function returns the character at a specified index in the string.

String str = "Hello World";
char ch = str.charAt(0);
System.out.println("First character of the string is " + ch); //Output : First character of the string is H

substring(): This function returns a substring of the original string, starting from the specified index and going up to (but not including) the end of the string, or up to a specified ending index.

String str = "Hello World";
String sub1 = str.substring(0, 5);
String sub2 = str.substring(6);
System.out.println("Substring 1 is " + sub1);
System.out.println("Substring 2 is " + sub2);
//output
//Substring 1 is Hello
//Substring 2 is World

concat(): This function concatenates two strings together.

String str1 = "Hello";
String str2 = "World";
String result = str1.concat(str2);
System.out.println("Concatenated string is " + result); //Output : Concatenated string is HelloWorld

equals(): This function compares two strings for equality and returns a boolean value indicating whether they are equal.

String str1 = "Hello";
String str2 = "Hello";
boolean result = str1.equals(str2);
System.out.println("Strings are equal: " + result); //Output : Strings are equal: true

indexOf(): This function returns the index of the first occurrence of a specified substring within the original string.

String str = "Hello World";
int index = str.indexOf("o");
System.out.println("Index of first occurrence of 'o' is " + index); //Output : Index of first occurrence of 'o' is 4

toLowerCase(): This function converts all characters in a string to lowercase.

String str = "Hello World";
String result = str.toLowerCase();
System.out.println("Lowercase string is " + result);
//Output:
//Lowercase string is hello world

toUpperCase(): This function converts all characters in a string to uppercase.

String str = "Hello World";
String result = str.toUpperCase();
System.out.println("Uppercase string is " + result);
//Output:
//Uppercase string is HELLO WORLD

trim(): This function removes any leading or trailing whitespace characters from a string.

String str = "  Hello World  ";
String result = str.trim();
System.out.println("Trimmed string is " + result);
//Output:
//Timmed string is Hello World

replace(): This function replaces all occurrences of a specified character or substring within a string with another specified character or substring.

String str = "Hello World";
String result = str.replace("o", "x");
System.out.println("Replaced string is " + result)