Strings and String Functions in Java
What is a String in Java?
In Java, a string is a sequence of characters. The String class is used to represent strings in Java. Strings in Java are immutable, which means that once a string is created, it cannot be changed. Instead, any operation that appears to modify a string actually creates a new string. For example, the following code creates two separate string objects:
String str1 = "Hello";
String str2 = str1 + " world"; // creates a new string object
System.out.println(str1); // "Hello"
System.out.println(str2); // "Hello world"
String Functions in Java
The String class provides many useful functions for working with strings in Java. Here are some of the most commonly used functions:
length()
: returns the length of the stringcharAt(int index)
: returns the character at the specified indexindexOf(String str)
: returns the index of the first occurrence of the specified substringsubstring(int beginIndex, int endIndex)
: returns a substring of the original stringtoUpperCase()
: returns a new string with all characters converted to uppercasetoLowerCase()
: returns a new string with all characters converted to lowercasereplace(char oldChar, char newChar)
: returns a new string with all occurrences of the old character replaced by the new characterreplaceAll(String regex, String replacement)
: returns a new string with all occurrences of the regular expression replaced by the replacement string
Here's an example that demonstrates some of these functions:
String str = "Hello, world!";
System.out.println("Length: " + str.length()); // 13
System.out.println("Character at index 1: " + str.charAt(1)); // 'e'
System.out.println("Index of first 'o': " + str.indexOf("o")); // 4
System.out.println("Substring from index 7 to end: " + str.substring(7)); // "world!"
System.out.println("Uppercase: " + str.toUpperCase()); // "HELLO, WORLD!"
System.out.println("Lowercase: " + str.toLowerCase()); // "hello, world!"
System.out.println("Replace 'o' with 'x': " + str.replace('o', 'x')); //
System.out.println("Replace all 'l' with 'x': " + str.replaceAll("l", "x")); // "Hexxo, worxd!"
System.out.println("Replace all vowels with '*': " + str.replaceAll("[aeiou]", "*")); // "H*ll*, w*rld!"
The first call to the replaceAll()
function replaces all occurrences of the character 'o' with 'x'. The second call replaces all occurrences of the character 'l' with 'x'. Note that the regular expression in the third call matches any vowel, and replaces it with the character '*'. Regular expressions are a powerful tool for working with strings in Java.
Conclusion
Strings are a fundamental data type in Java, and the String class provides many useful functions for working with strings. By understanding how to use these functions, you can manipulate strings in a variety of ways to suit your needs.
Comments
Post a Comment