0% found this document useful (0 votes)
11 views7 pages

Java String Library Functions Guide

The document outlines important string library functions in Java, including methods like length(), charAt(), substring(), and others, along with their descriptions and examples. It also presents frequently asked string interview questions with solutions, such as reversing a string, checking for anagrams, and counting character frequency. Overall, it serves as a comprehensive guide for understanding string manipulation in Java.

Uploaded by

razakroq44
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views7 pages

Java String Library Functions Guide

The document outlines important string library functions in Java, including methods like length(), charAt(), substring(), and others, along with their descriptions and examples. It also presents frequently asked string interview questions with solutions, such as reversing a string, checking for anagrams, and counting character frequency. Overall, it serves as a comprehensive guide for understanding string manipulation in Java.

Uploaded by

razakroq44
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Important String Library Functions in Java

1. length()

●​ Description: Returns the length of the string.

Example:​
java​
Copy code​
String str = "Hello";
[Link]([Link]()); // Output: 5

●​

2. charAt(int index)

●​ Description: Returns the character at the specified index.

Example:​
java​
Copy code​
String str = "Hello";
[Link]([Link](1)); // Output: e

●​

3. substring(int beginIndex, int endIndex)

●​ Description: Returns a substring from beginIndex (inclusive) to endIndex


(exclusive).

Example:​
java​
Copy code​
String str = "Hello World";
[Link]([Link](0, 5)); // Output: Hello

●​

4. contains(CharSequence sequence)

●​ Description: Checks if the string contains the specified sequence.


Example:​
java​
Copy code​
String str = "Hello World";
[Link]([Link]("World")); // Output: true

●​

5. toLowerCase() and toUpperCase()

●​ Description: Converts the string to lowercase or uppercase.

Example:​
java​
Copy code​
String str = "Hello World";
[Link]([Link]()); // Output: hello world
[Link]([Link]()); // Output: HELLO WORLD

●​

6. trim()

●​ Description: Removes leading and trailing whitespace from the string.

Example:​
java​
Copy code​
String str = " Hello World ";
[Link]([Link]()); // Output: Hello World

●​

7. equals() and equalsIgnoreCase()

●​ Description: Compares two strings for equality, case-sensitive (equals()) or


case-insensitive (equalsIgnoreCase()).

Example:​
java​
Copy code​
String str1 = "Hello";
String str2 = "hello";
[Link]([Link](str2)); // Output: false
[Link]([Link](str2)); // Output: true

●​

8. replace(char oldChar, char newChar)

●​ Description: Replaces occurrences of a character with another character.

Example:​
java​
Copy code​
String str = "Hello World";
[Link]([Link]('o', 'a')); // Output: Hella Warld

●​

9. split(String regex)

●​ Description: Splits the string around matches of the regex.

Example:​
java​
Copy code​
String str = "Java is fun";
String[] words = [Link](" ");
for (String word : words) {
[Link](word);
}
// Output:
// Java
// is
// fun

●​

10. indexOf() and lastIndexOf()

●​ Description: Finds the first or last occurrence of a character or substring.

Example:​
java​
Copy code​
String str = "Hello World";
[Link]([Link]('o')); // Output: 4
[Link]([Link]('o')); // Output: 7

●​

Frequently Asked String Interview Questions

1. Reverse a String

Problem: Write a program to reverse a string without using the reverse function. Solution:

java
Copy code
public class ReverseString {
public static void main(String[] args) {
String str = "Interview";
StringBuilder reversed = new StringBuilder();
for (int i = [Link]() - 1; i >= 0; i--) {
[Link]([Link](i));
}
[Link]("Reversed String: " + reversed);
}
}

2. Check if Two Strings are Anagrams

Problem: Write a program to check if two strings are anagrams.​


Solution:

java
Copy code
import [Link];

public class AnagramCheck {


public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";

char[] arr1 = [Link]();


char[] arr2 = [Link]();
[Link](arr1);
[Link](arr2);

if ([Link](arr1, arr2)) {
[Link]("The strings are anagrams.");
} else {
[Link]("The strings are not anagrams.");
}
}
}

3. Count the Frequency of Characters in a String

Problem: Write a program to count the frequency of each character in a string.​


Solution:

java
Copy code
import [Link];

public class CharFrequency {


public static void main(String[] args) {
String str = "hello world";
HashMap<Character, Integer> freq = new HashMap<>();

for (char c : [Link]()) {


[Link](c, [Link](c, 0) + 1);
}

[Link](freq);
}
}

4. Check if a String is a Palindrome


Problem: Write a program to check if a string is a palindrome.​
Solution:

java
Copy code
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();

if ([Link](reversed)) {
[Link]("The string is a palindrome.");
} else {
[Link]("The string is not a palindrome.");
}
}
}

5. Find the Longest Palindromic Substring

Problem: Write a program to find the longest palindromic substring in a string.​


Solution:

java
Copy code
public class LongestPalindrome {
public static void main(String[] args) {
String str = "babad";
String result = "";

for (int i = 0; i < [Link](); i++) {


for (int j = i; j < [Link](); j++) {
String sub = [Link](i, j + 1);
if (isPalindrome(sub) && [Link]() >
[Link]()) {
result = sub;
}
}
}
[Link]("Longest Palindromic Substring: " +
result);
}

public static boolean isPalindrome(String s) {


return [Link](new StringBuilder(s).reverse().toString());
}
}

6. Count Vowels and Consonants

Problem: Write a program to count vowels and consonants in a string.​


Solution:

java
Copy code
public class VowelConsonantCount {
public static void main(String[] args) {
String str = "Java Programming";
int vowels = 0, consonants = 0;

for (char c : [Link]().toCharArray()) {


if (c >= 'a' && c <= 'z') {
if ("aeiou".indexOf(c) != -1) {
vowels++;
} else {
consonants++;
}
}
}

[Link]("Vowels: " + vowels);


[Link]("Consonants: " + consonants);
}
}

Common questions

Powered by AI

The trim() method in Java's String class is used to remove leading and trailing whitespace from a string. This can be effective in cleaning user inputs or database entries where extra spaces may be inadvertently included. For example, ' Hello World ' becomes 'Hello World' after applying trim().

Use the toLowerCase() method to transform all characters of a string to lowercase. This is beneficial for standardizing data before analysis or comparison operations, especially when case insensitivity is required, such as comparing user inputs or ensuring consistent data storage .

You can find the longest palindromic substring by iterating through each character of the string, checking all possible substrings, and validating if they are palindromes. Use two nested loops to generate substrings, and for each substring, check if it is a palindrome by comparing it to its reverse (obtained using StringBuilder.reverse()). Track the longest palindrome found .

The split(String regex) method can be used to tokenize a sentence into words based on a specified delimiter pattern, such as whitespace. While using split, ensure that the regex accurately matches the intended delimiter; using " " will split on single spaces, whereas "\s+" matches multiple whitespace characters effectively handling irregular spaces .

To check if a string is a palindrome in Java, reverse the string using StringBuilder.reverse() and compare it to the original string using equals(). If both are equal, the string is a palindrome. This method effectively deals with both efficiency and simplicity .

The substring(beginIndex, endIndex) method in Java extracts a portion of a string starting at beginIndex (inclusive) and ending at endIndex (exclusive). To avoid errors, ensure indices are within bounds of the string length and that beginIndex is less than or equal to endIndex .

Reverse a string by iterating from the last index to the first index and append each character to a StringBuilder. This approach avoids using the built-in reverse(), providing a manual method that demonstrates control over string traversal and manipulation .

To determine if two strings are anagrams in Java, you can convert both strings to character arrays using toCharArray(), sort the arrays with Arrays.sort(), and check for equality using Arrays.equals(). If sorted character arrays of both strings are equal, the strings are anagrams .

Use a HashMap<Character, Integer> to count character frequency in a string. Iterate through the string, convert it to a character array, and populate the HashMap. Update the count for each character using getOrDefault() to handle new entries with a default of 0 .

To compare two strings for equality in a case-sensitive manner, use the equals() method, and for a case-insensitive comparison, use the equalsIgnoreCase() method. equals() considers the content and case as distinct, while equalsIgnoreCase() ignores case differences .

You might also like